java - 如何在 spring 项目中正确注入(inject) @Autowired 依赖而不使用 getBean?是否可以?

标签 java spring jdbc dependencies code-injection

1 - 我想用 @Autowired 注入(inject)“loginService”而不调用 getBean,但不起作用。它为空。只能与 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;
}

}

用户DAO

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 );
        }
    }
}

登录服务-接口(interface)

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

登录服务Impl

@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;
    }

}

在下面的类中,即使使用 @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是否好。

我希望得到一些帮助。

谢谢。

最佳答案

如果 Spring 没有创建您的对象,它就无法将依赖项注入(inject)到它们中。

您需要从容器中获取 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();
    }
}

关于java - 如何在 spring 项目中正确注入(inject) @Autowired 依赖而不使用 getBean?是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40848803/

相关文章:

java - 是否有一种在 Firebase 图像上显示边界框的简单方法

java - 如何提及类路径

java - 映射者 : Hibernate

java - JDBC,Java调用Sqlserver存储过程

java - 已签名的 APK 具有不同的 Facebook key 哈希

java - 更改 IntelliJ IDEA 中的 VM 设置 : Error occurred during initialization of VM

java - 编写可扩展的网络应用程序/网络服务的书

java - 如何将 @ManagedAttribute 和 @ManagedOperation 添加到扩展另一个类的 MBean

java - 如何向 Oracle 触发器发送任意参数?

java - 如何将数据从 MySQL 查询传递到结果集?