Spring学习(一)
第一章 Spring的jar包导入、配置文件和ioc基本用法(setter注入)
一、jar包导入
Spring相关jar包下载地址:
https://repo.spring.io/release/org/springframework/spring
选择4.3.5版本,下载zip结尾的文件
将spring-framework-4.2.5.RELEASE下libs文件夹贴到项目中,并引入jar包。
二、ioc基本用法(setter注入)
在项目中创建和src平级的resource文件夹,创建spring-ioc.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">
</beans>
创建bean文件夹,声明一个HelloWorld类,定义name属性,生成对应的get&set方法,toString方法以及全参和无参构造函数,并定义一个方法随意输出一些东西:
public class HelloWorld {
private String name;
public HelloWorld() {
}
public HelloWorld(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "HelloWorld{" +
"name='" + name + '\'' +
'}';
}
public void say(){
System.out.println("hello" + name);
}
}
在spring-ioc.xml中,添加配置:
<bean id="suiYi" class="com.bean.HelloWorld"/>
通过ioc容器取到方法:
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-ioc.xml");
并用junit进行单元测试,:
public class HelloWorldTest {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-ioc.xml");
@Test
public void say() {
HelloWorld helloWorld = (HelloWorld) beanFactory.getBean("suiYi");
helloWorld.setName("666");
System.out.println(helloWorld);
}
}
测试方法无误:
这种注入方式要求对应的类中要含有set方法,当类中没有对应的set方法时,也可以选用构造函数注入的方式,这里先不做介绍。
总结
以上就是今天要讲的内容。