内容来自传智博客视频:
属性注入的四种方法:
- 使用有参构造方法注入属性
- 使用set方式注入属性
- 注入对象类型属性
- P名称空间的注入
spring的配置文件bean1.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">
<bean id="user1" class="ioc.User"></bean>
<!-- 1.使用有参构造注入属性 -->
<bean id="demo1" class="property.PropertyDemo1">
<!-- 使用有参构造输入 -->
<constructor-arg name="userName" value="小王小马"></constructor-arg>
</bean>
<!-- 2.使用set方法注入属性 -->
<bean id="book" class="property.Book">
<!-- 注入属性值 name=属性值,类里面定义的属性名称 value属性:设置具体的值 -->
<property name="bookName" value="学会提问"></property>
</bean>
<!-- 3.注入对象类型的属性 -->
<!-- 配置service和dao对象 -->
<bean id="userDao" class="ioc.UserDao"></bean>
<bean id="userService" class="ioc.UserService">
<!-- 注入Dao对象 ,ref的值是Dao配置bean中的id值-->
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
1.使用有参构造方法设置属性:
(1)包含有参构造方法的类,使用的是配置文件bean1.xml中的“使用有参构造注入属性”下的配置:
package property;
public class PropertyDemo1 {
public String userName;
public PropertyDemo1(String userName){
this.userName = userName;
}
public void test1(){
System.out.println("userName:"+userName);
}
}
(2)测试类
package ioc;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import property.Book;
import property.PropertyDemo1;
import bean.BeanStatic;
import bean.BeanInstance;
public class TestIOC {
@Test
public void testUser(){
//1.加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
PropertyDemo1 demo1 = (PropertyDemo1) context.getBean("demo1");
demo1.test1();
}
2.使用set方式注入属性
(1)包含set方法的类,使用的是配置文件bean1.xml中的“使用set方法注入属性”下的配置:
package property;
public class Book {
private String bookName;
public void setBookName(String bookName) {
this.bookName = bookName;
}
public void demoBook(){
System.out.println("bookName:"+bookName);
}
}
(2)测试类
package ioc;
public class TestIOC {
@Test
public void testUser(){
//1.加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
Book book = (Book) context.getBean("book");
book.demoBook();
}
3.注入对象类型属性,使用的是配置文件bean1.xml中的“注入对象类型的属性”下的配置
(1)服务类
package ioc;
public class UserService {
private UserDao userDao;
public void add(){
System.out.println("service..........");
userDao.add();
}
/**
* @param userDao 要设置的 userDao
*/
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
(2)数据类
package ioc;
public class UserDao {
public void add(){
System.out.println("dao...............");
}
}
(3)测试类
package ioc;
public class TestIOC {
@Test
public void testUser(){
//1.加载spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = (UserService) context.getBean("userService");
userService.add();
}