0.常见2种注入方式
0.1 构造方法注入
0.2 setter方法注入
1.构造方法注入
1.1 实例化对象注入
public void testSave4() {
UserDao userDao = new UserDaoImpl("DI");
userDao.save();
}
1.2 Spring注入
<bean id="userDao" class="com.boomsecret.ioc.UserDaoImpl">
<constructor-arg index="0" type="java.lang.String" value="DI"/>
</bean>
public void testSave5() {
String configPath = "com/boomsecret/ioc/bean.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(configPath);
UserDao userDao = applicationContext.getBean("userDao", UserDao.class);
userDao.save();
}
2.setter方法注入
2.1 直接调用setter方法注入
public void testSave4() {
UserDaoImpl userDaoImpl = new UserDaoImpl();
userDaoImpl.setDefaultValue("DI");
userDaoImpl.save();
}
2.2 Spring注入
<bean id="userDao" class="com.boomsecret.ioc.UserDaoImpl">
<property name="defaultValue" value="DI"></property>
</bean>
public void testSave5() {
String configPath = "com/boomsecret/ioc/bean.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(configPath);
UserDao userDao = applicationContext.getBean("userDao", UserDao.class);
userDao.save();
}