开发者

spring 3 Dependency injection( IoC) with annotation

开发者 https://www.devze.com 2023-04-04 11:41 出处:网络
@Named(\"loginDetailsService\") public class LoginDetailsServiceImpl implements LoginDetailsService { @Inject
@Named("loginDetailsService")
public class LoginDetailsServiceImpl implements LoginDetailsService {

    @Inject
    @Named("loginDetailsDAO")
    private LoginDetailsDAO loginDetailsDAO;

    public List<UserLogin> loginDetails(UserLogin login) {
        return loginDetailsDAO.loginDetails(login);
    }


public class LoginDetailsDAOImpl extends HomeSessionFactory implements LoginDetailsDAO {


    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public List<UserLogin> loginDetails(UserLogin login) {
        session = sessionFactory.openSession();
        Query query = null;
        try {
                 // blah...
            } catch(Exception e){
         }
        return query.list();
}


public abstract class HomeSessionFactory {

    @Inject
    @Named("sessionFactory")
    protected SessionFactory sessionFactory;
    protected Session session;  
}

spring context file:

<context:component-scan base-package="com.home.app" />

in some example i found that using setter method for loginDetailsDAO as setLoginDetailsDAO(...){..}

is it required to use setter method? when it is required to use getter/se开发者_如何学运维tter? if I don't what will happen? is there any modification required for the above code as per spring3.x format?

without setter method i am able to connect DAO implementation.


If you're going with annotations--I highly recommend this--then you can either annotate fields, setters, or constructors. Only the thing that you put the annotation on is required. If a field, it will be set directly in the field using reflection. If a setter, that method will be called with the dependency. If a constructor--and this is the option that I highly recommend--then the constructor will be called with all appropriate dependencies.

I strongly recommend constructor injection because it moves us back toward real object-oriented programming in Java, where the job of a constructor is to create an object in a valid state. It makes it impossible for the class to be used either in or out of Spring--and most notably in unit tests--without providing all the required dependencies.


The nice thing about using setter methods is that you can programmatically inject mock dependencies in unit tests. That's all (for me at least).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号