使用步骤说明
1,下载jar包。
2,创建一个实体类。
3,编写Spring配置文件。
4,编写测试代码通过Spring进行属性注入。
1,下载相关jar包
网址:https://maven.springframework.org/release/org/springframework/spring/
解压后:
spring框架依赖jar包说明:
1,spring-core-5.2.2.RELEASE.jar:Spring框架核心jar包。是其他组件的基本核心,包含基本核心工具类。
2,spring-beans-5.2.2.RELEASE.jar:包含Spring框架管理Bean和配置文件的基本功能。
3,spring-context-5.2.2.RELEASE.jar:Spring框架核心包的扩展包,包含大量工具类。
4,spring-expression-5.2.2.RELEASE.jar:Spring框架中一个强大的表达式解析语言,支持在运行时动态解析表达式给对象赋值等功能。
编写一个实体类
/**
* 实体类
*/
public class HelloSpring {
//定义hello属性,该属性的值将通过Spring框架进行设置。
private String hello;
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
/**
* 输出方法,从spring配置文件中获取属性并输出。
*/
public void print(){
System.out.println("Spring say:,"+this.getHello()+"!");
}
}
3,编写Spring配置文件
在项目根路径下创建resources目录,并将Spring配置文件–applicationContext.xml 创建在其根路径下。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation=
"http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--通过bean元素声明需要spring创建的实例,该实例类型通过class属性指定,
并通过id的属性为该实例指定一个名称(自定义且唯一),以便于程序中使用-->
<bean id="hello" class="com.company.pojo.HelloSpring">
<!-- property元素用来为实例的属性赋值,此处调用setHello()方法实现赋值操作
name属性对应setter方法 -->
<property name="hello" >
<!--value标签设置属性值-->
<value>反转的人生,经过妍</value>
</property>
</bean>
</beans>
4,编写测试类
@Test
public void testHello(){
//通过ClassPathXmlApplicationContext实例化上下文
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//通过ApplicationContext的getBean()方法,根据id获取bean实例
HelloSpring hello=(HelloSpring)context.getBean("hello");
//执行打印方法
hello.print();
}
解释:
1,ApplixationContext是一个接口,负责读取Spring配置文件,管理对象的加载,生成,维护Bean对象与Bean对象之间的依赖关系,负责Bean的声明周期等。
2,ClassPathXmlApplicationContext是ApplixationContext接口的实现类,用于从classpath路径中读取Spring配置文件。