简体   繁体   中英

spring 3 Dependency injection( IoC) with annotation

@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/setter? 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.

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).

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM