1、手动注入
(1)set注入
public class UserService { private UserDao userDao; public void setUserDao(UserDao dao){ this.userDao = dao; } }
<bean id="userDao1" class="com.spring1.dao.UserDao"></bean> <bean id="userService" class="com.spring1.service.UserService"> <property name="userDao" ref="userDao1"></property> </bean>
通过userService对象的setUserDao方法,将userDao1注入进去。
public class User { int id; String name; String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
public class UserDao { public void setShowUser(User user){ System.out.println(user.getId()+":"+user.getName()+":"+user.getPassword()); } }
<bean id="user" class="com.spring1.entity.User"> <property name="id" value="1"></property> <property name="name" value="zhangsan"></property> <property name="password" value="123456"></property> </bean> <bean id="userDao1" class="com.spring1.dao.UserDao"> <property name="showUser" ref="user"></property> </bean>
在bean配置中对user初始化,userDao1通过自己的setShowUser方法将user注入
(2)构造方法注入
<bean id="userDao1" class="com.spring1.dao.UserDao"> </bean> <bean id="testService" class="com.spring1.service.UserService"> <constructor-arg name="userDao1" ref="userDao1"></constructor-arg> </bean>
@Test public void test() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService service = (UserService) ac.getBean("testService"); service.showUser(); }
public class UserService { private UserDao userDao; public UserService(UserDao userDao1){ this.userDao = userDao; } public void showUser(){ System.out.print("ok-------------"); } }
构造函数参数的名字,要与类的构造参数的名字对应。
2、自动注入
<bean id="userDao2" class="com.spring1.dao.UserDao"></bean> <bean id="testService" class="com.spring1.service.UserService" autowire="byName"> </bean>
id=userDao2,下边的setUserDao2==userDao2是一样的。
public class UserService { private UserDao userDao; public void setUserDao2(UserDao userDao1){ this.userDao = userDao1; } public void showUser(){ userDao.showUser(); } }
byname自动注入的时候,就要顶一个一个name=类中的参数名字的bean
时间: 2024-10-15 16:03:10