spring(2)——通过配置文件使用类,实现控制反转,实现不同的操作只需要在xml文件中进行修改
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了spring(2)——通过配置文件使用类,实现控制反转,实现不同的操作只需要在xml文件中进行修改,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2212字,纯文字阅读大概需要4分钟。
内容图文
1.在maven中的pom.xml中导入spring依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
2.编写实体类
实体类一定要有get和set方法
package com.lixv.entity;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
package com.lixv.entity;
public class HelloSpring {
private String springStr;
private Hello hello;
public String getSpringStr() {
return springStr;
}
public void setSpringStr(String springStr) {
this.springStr = springStr;
}
public Hello getHello() {
return hello;
}
public void setHello(Hello hello) {
this.hello = hello;
}
@Override
public String toString() {
return "HelloSpring{" +
"springStr='" + springStr + '\'' +
", hello=" + hello +
'}';
}
}
3.在resources中新增一个beans.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 使用spring来创建对象,在spring这些都称为bean -->
<bean id="hello" class="com.lixv.entity.Hello">
<property name="str" value="Spring"/>
</bean>
<bean id="helloSpring" class="com.lixv.entity.HelloSpring">
<property name="springStr" value="springstr"/>
<property name="hello" ref="hello"/>
</bean>
</beans>
- beans标签是spring的专有标签,它的各个属性是固定的。
- bean标签的id是实体类的名字,clsss是实体类的类型。
- property标签的name属性是类的属性名,value是赋值给这个属性的值,ref指向已经定义好的bean的id。
4.测试代码
package com.lixv.dao;
import com.lixv.entity.Hello;
import com.lixv.entity.HelloSpring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
public static void main(String[] args) {
//通过xml文件获取spring的beans
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//获取beans中的bean
HelloSpring hellospring = (HelloSpring) context.getBean("helloSpring");
System.out.println(hellospring);
}
}
运行结果:
内容总结
以上是互联网集市为您收集整理的spring(2)——通过配置文件使用类,实现控制反转,实现不同的操作只需要在xml文件中进行修改全部内容,希望文章能够帮你解决spring(2)——通过配置文件使用类,实现控制反转,实现不同的操作只需要在xml文件中进行修改所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。