![](/img/trans.png)
[英]Create an Object in Spring with annotations (Inject, Autowired) or with getBean
[英]How can i correctly inject dependency with @Autowired in the spring project without use getBean? Is it Possible?
1-我想在不調用getBean的情況下使用@Autowired注入“ loginService”,但無法正常工作。 它為空。 僅適用於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 );
}
}
}
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;
}
}
在跟隨類中,即使使用@ 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,但是我不知道這種方法是否很好。
我將不勝感激。
謝謝。
只有當您用@Service
或@Controller
標記類時,Spring容器才會注入依賴項(等。 @Controller
stereotype
注釋請@Controller
此處 )。 因此,您需要使用@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 context
獲取TestLoginService
bean對象。
ApplicationLauncher類:
public class ApplicationLauncher {
public static void main(String[] args) {
applicationContext = LoadPoolConnection.getApplicationContext();
TestLoginService testLoginService = (TestLoginService)applicationContext.
getBean("testLoginService");
testLoginService.doLogin();
}
}
如果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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.