一:setter中注入:property
perperty用来注入属性,属性可以是常见数据类型,也可以是自定义的内置对象
<!-- 相当于调用了无参构造,实例化了u1对象-->
<bean id="u1" class="com.rt.springdemo.dao.impl.UserDAOImpl"></bean>
<!-- bean标签中id=XXX或者name=XXX,作用基本一样,name可以加入一些特殊字符 -->
<bean name="userService01" class="com.rt.springdemo.service.UserService" scope="singleton">
<!--1.property这句就相当于设置了属性,也就是调用 set【UserDao】(【u1】) -->
<property name="userDAO" ref="u1" />
<!--2.property去注入一个属性,也是要去调用setter-->
<property name="propertyInj" value="新注入的属性值" />
</bean>
service层:
public class UserService {
private IUserDAO userDAO; //xml中,"u1"对应class="com.rt.springdemo.dao.impl.UserDAOImpl",将注入在此
public void add(User user) {//test调用这个add方法
userDAO.save(user);
}
public IUserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(IUserDAO userDAO) {//xml中调用的方法
this.userDAO = userDAO;
}
//2属性注入
private String propertyInj;//
public String getPropertyInj() {
return propertyInj;
}
public void setPropertyInj(String propertyInj) {
this.propertyInj = propertyInj;
System.out.println("属性注入--"+propertyInj);
}
}
二:构造函数中注入:constructor-arg
相当于在调用构造函数的时候,把实例注入
<bean name="userService01" class="com.rt.springdemo.service.UserService">
<!--3.constructor-arg相当于调用构造函数: public 【UserService】(IUserDAO 【u1】) -->
<constructor-arg>
<ref bean="u1"/>
</constructor-arg>
</bean>
service层:
//3构造
public UserService()
{
}
public UserService(IUserDAO user)//构造时注入
{
user.save(new User());
}
三:注入范围:scope
bean注入时的模式选项:
scope默认是"singleton" 单例模式; "prototype" 是每次都new一个新的实例
<!-- scope默认是"singleton" 单例模式; "prototype" 是每次都new一个新的实例-->
<bean name="userService01" class="com.rt.springdemo.service.UserService" scope="prototype">
//scope为“singleton”单例 ,或“prototype”每次都分配新的
UserService service02 = (UserService)ctx.getBean("userService01");
System.out.println("scope=> "+ (service02 == service01));
四:autowire
xml里的autowire也有byName和byType两种方法,
一来不如Annotation里边的那种常用,二来名字或者类型重复了还得指定,比较费篇幅
有时间再来补
五:lazy-init,延迟加载
就是初始化时指定调用一个加载的方法,结束时候也指定一个方法。
<bean name="userService01" class="com.rt.springdemo.service.UserService" scope="singleton" init-method="UserInit" destroy-method="UserDestroy">
service层
//lazy-init
public void UserInit()
{
System.out.println("调用初始");
}
public void UserDestroy()
{
System.out.println("调用销毁");
}
必须明确写出destroy方法,且必须用ClassPathXmlApplicationContext类型
//必须明确写出destroy方法,且context必须用ClassPathXmlApplicationContext类型
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("springBeans.xml");
ctx.destroy();