如何在不使用getBean的情况下在spring项目中正确地使用@Autowired注入依赖?可能吗?

时间:2016-11-28 16:12:42

标签: java spring jdbc dependencies code-injection

1 - 我想在不调用getBean的情况下使用@Autowired注入“loginService”,但是无法正常工作。它是null。仅适用于getBean。 我会很感激一些解释。

SpringContext.xml

<!-- to activate annotations in beans already registered in the application context -->
<context:annotation-config />

<!-- scans packages to find and register beans within the application context -->
<context:component-scan base-package="br.com.cpb.gsa" />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver" />
    <property name="url" value="jdbc:jtds:sqlserver://myserver:1433;databaseName=" />
    <property name="username" value="" />
    <property name="password" value="" />
</bean>

LoadPoolConnection - 加载SpringContext(我不知道这个类是否需要是静态的)

public class LoadPoolConnection {

private static ApplicationContext applicationContext;

static {

    applicationContext = new ClassPathXmlApplicationContext("br/com/cpb/gsa/SpringContext.xml");

}

public static ApplicationContext getApplicationContext() {
    return applicationContext;
}

}

UserDAO的

public interface UserDAO{

    public Usuario getAuthenticatedUser( String login );

}

在UserDAOImpl

@Repository("userDAO")
public class UserDAOImpl implements UserDAO {

    @Autowired
    private DataSource dataSource;

    @Override
    public Usuario getAuthenticatedUser(String login) {

        try (Connection conn = dataSource.getConnection()){

            //... sample code, just for explanation ...
            Usuario user = new Usuario();
            user.setLogin("test");

            return user;

        } catch (SQLException e) {
            throw new RuntimeException( e );
        }
    }
}

LoginService - 接口

public interface LoginService {
    public Usuario doLogin(Usuario user);   
}

LoginServiceImpl

@Service("loginService")
public class LoginServiceImpl implements LoginService, Serializable {

    private static final long serialVersionUID = 4014652022146807624L;

    @Autowired
    private UserDAO userDAO;

    public Usuario doLogin(Usuario user){

        if ((user == null) ||              (JavaUtil.isNull(user.getLogin(),"").trim().length() == 0)){
            throw new RuntimeException(Constant.LOGIN_OR_PASSWORD_NOT_PROVIDED);
        }

        //UsuarioDAO dao = (UsuarioDAO)     applicationContext.getBean("usuarioDAO");   
        Usuario savedUser = userDAO.getAuthenticatedUser(user.getLogin());  

        if  ( (savedUser == null) || (!savedUser.getSenha().equals(user.getSenha())) ){
            throw new RuntimeException(Constant.INVALID_USER_OR_PASSWORD);
        }

        return user;
    }

}

在follow class中,即使使用@Autowired

,loginService也为null
public class TestLoginService {

    private static ApplicationContext applicationContext;

    @Autowired
    private static LoginService loginService;

    private static void doLogin(){

        Usuario user = new Usuario();
        user.setLogin("weles");
        user.setSenha("test");

        //loginService = (LoginService) applicationContext.getBean("loginService");  //with this command works, but i would like don´t user this call.

        Usuario savedUser = loginService.doLogin(user);
        System.out.println(savedUser.getLogin());
    }

    public static void main(String[] args) {

        applicationContext = LoadPoolConnection.getApplicationContext();
        doLogin();

    }

}

将来我想使用Pool,因此我使用LoadPoolConnection,但我不知道这个appoach是否合适。

我将不胜感激。

感谢。

2 个答案:

答案 0 :(得分:1)

Spring容器仅在您使用@Service@Controller(等等。stereotype注释看here)标记类时才注入依赖项。 因此,您需要使用@Service标记TestLoginService,以便为@Autowired字段执行字段注入。

因此,您需要更改TestLoginService课程,如下所示:

@Service
public class TestLoginService {

    @Autowired
    private LoginService loginService;

    private void doLogin(){

        Usuario user = new Usuario();
        user.setLogin("weles");
        user.setSenha("test");

        Usuario savedUser = loginService.doLogin(user);
        System.out.println(savedUser.getLogin());
    }
}

如果你想单独维护TestLoginService类,那么你肯定需要ApplicationLauncher类,如下所示,然后你需要通过spring TestLoginService获取context bean对象

ApplicationLauncher类:

public class ApplicationLauncher {

     public static void main(String[] args) {
             applicationContext = LoadPoolConnection.getApplicationContext();
             TestLoginService testLoginService = (TestLoginService)applicationContext.
                       getBean("testLoginService"); 
             testLoginService.doLogin();
     }
}

答案 1 :(得分:1)

如果Spring没有创建对象,则无法将依赖项注入其中。

您需要从容器中获取TestLoginService的实例 - 它将正确初始化。

@Service
public class TestLoginService {
    @Autowired
    private LoginService loginService;

    private void doLogin(){
        Usuario user = new Usuario();
        user.setLogin("weles");
        user.setSenha("test");

        Usuario savedUser = loginService.doLogin(user);
        System.out.println(savedUser.getLogin());
    }

    public static void main(String[] args) {
         applicationContext = LoadPoolConnection.getApplicationContext();

         applicationContext.getBean(TestLoginService.class).doLogin();
    }
}