【问题标题】:How can i correctly inject dependency with @Autowired in the spring project without use getBean? Is it Possible?如何在不使用 getBean 的情况下在 spring 项目中使用 @Autowired 正确注入依赖项?可能吗?
【发布时间】:2017-04-12 10:35:03
【问题描述】:

1 - 我想用@Autowired 注入“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 );

}

用户DAOImpl

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

登录服务实现

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

}

在后续类中,loginService 为空,即使使用 @Autowired

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,但我不知道这个方法是否好。

我将不胜感激。

谢谢。

【问题讨论】:

  • 删除static。您不能注入静态字段。除此之外,您的 TestLoginService 永远不会被注入,因为它不是 Spring 管理的 bean。

标签: java spring jdbc dependencies code-injection


【解决方案1】:

只有当你的类被标记为@Service@Controller(等等。stereotype 注解看起来here)时,Spring 容器才会注入依赖项。 因此,您需要使用@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类,如下图,然后你需要通过springcontext获取TestLoginServicebean对象。

ApplicationLauncher 类:

public class ApplicationLauncher {

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

【讨论】:

  • 您的示例无法编译(您从静态方法访问非静态变量)。
【解决方案2】:

如果 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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 2020-10-25
    • 2016-05-19
    • 1970-01-01
    相关资源
    最近更新 更多