Method injection is rarely used in spring, where the main application is that a protected abstract method may be defined in the object, and the container may implement it at runtime to return the object that is queried by the container.
One of the best uses of method injection is to handle situations where a single state, stateless object needs to invoke a non-state, stateful, or non-thread-safe object.
When you first contacted spring, if you called a singleton bean in a single instance bean, you would simply set the non-single instance bean to False. In fact, we thought, we created a single instance object, and the other beans used in this single object would only be created once--(most of the time, of course, that's the problem we're trying to solve). So, simply setting the property singleton of a non-single instance bean to False is not a solution. This is the time to inject your talents into the process.
The following example is the case of a single instance invocation: We call the DAO layer at the service level
/**
*@authorzhu国辉
*/
packagecom.zgh.spring.dao;
importjava.util.List;
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;< BR> /**
*记住一定要引入org.springframework.orm. (hibernate3).support.HibernateDaoSupport
*也就是此类的父类.
*@authorzhu国辉
*
*/
publicclassUserLoginDaoextendsHibernateDaoSupportimplementsIUserLoginD ao{
inti=0;
publicListgetUser(Stringusername,Stringpassword){
System.out.println("i="+(++i));
System.out.println(username+":"+password);
Listusers=getHibernateTemplate().find ("fromUseruwhereusername=?andpassword=?",newObject[] {username,password});
returnusers;
}
}
To see the effect, we declared a member variable in the DAO (becomes a stateful bean)
Below is the service layer:
/**
*@authorzhu国辉
*/
packagecom.zgh.spring.service;
importjava.util.List;
importcom.zgh.spring.dao.IUserLoginDao;;
publicclassUserLoginServiceimplementsIUserLoginService{
privateIUserLoginDaouserLoginDao;
publicvoidsetUserLoginDao(IUserLoginDaouserLoginDao){
this.userLoginDao=userLoginDao;
}
publicListgetUser(Stringusername,Stringpassword){
returnuserLoginDao.getUser(username,password);
}
}