2016-11-28 3 views
0

1 - getBean을 호출하지 않고 @Autowired로 "loginService"를 주입하려고하지만 작동하지 않습니다. null입니다. getBean에서만 작동합니다. 몇 가지 설명을 부탁드립니다.getBean을 사용하지 않고 스프링 프로젝트에서 @Autowired를 사용하여 종속성을 올바르게 주입하려면 어떻게해야합니까? 가능한가?

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 interface UserDAO{ 

    public Usuario getAuthenticatedUser(String login); 

} 

public class LoadPoolConnection { 

private static ApplicationContext applicationContext; 

static { 

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

} 

public static ApplicationContext getApplicationContext() { 
    return applicationContext; 
} 

}

UserDAO (이 클래스의 요구가 정적 일 경우 내가 본건은 알고있다)

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 - 추적 클래스 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(); 

    } 

} 

으로, null의에서 인터페이스

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

} 

나야. uld는 Pool을 사용하고 싶습니다. 따라서 LoadPoolConnection을 사용하고 있습니다.하지만이 appoach가 좋은지 모르겠습니다.

몇 가지 도움을 주시면 감사하겠습니다.

감사합니다.

+1

'정적'을 제거하십시오. 정적 필드를 주입 ​​할 수 없습니다.그 다음으로'TestLoginService'는 Spring 관리 빈이 아니므로 결코 주입되지 않을 것입니다. –

답변

1

스프링 컨테이너 클래스가 @Service 또는 @Controller (등 stereotype 주석 here)을 보면 표시되어 있습니다 만 종속성을 주입한다. @Autowired 필드의 필드 주입을 실행하려면 TestLoginService를 @Service으로 표시해야합니다. 아래 그림과 같이

그래서 당신은 당신의 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 클래스가 필요하고 당신은 TestLoginService 빈을 얻을 필요 봄을 통해 물체 context.

ApplicationLauncher 클래스 : 봄이 객체를 생성하지 않는 경우

public class ApplicationLauncher { 

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

예제가 컴파일되지 않습니다 (정적 메소드에서 비 정적 변수에 액세스). – dunni

+0

정적 메서드가 인스턴스 필드를 참조 할 수 없습니다 ... – Grogi

1

, 그것은 그들에 종속성을 주입 할 수 없습니다.

컨테이너에서 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(); 
    } 
} 
관련 문제