2017-07-06 76 views
0

我想通過在我的bean配置中添加屬性來將字段變量自動裝入類中。這樣當Spring彈出的屬性中的值被實例化時,如何在春天自動裝配屬性

我的Spring配置文件是

<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> 

<bean id="authentication" class="com.quicut.model.authenticationModel"> 
    <property name="dbURL" value="jdbc:mysql://127.0.0.1:3306/quicut" /> 
    <property name="userN" value="user1" /> 
    <property name="userP" value="password" /> 
    <property name="JDBC_DRIVER" value="com.mysql.jdbc.Driver" /> 
</bean> 

,我創建了具有我想實例化時由彈簧賦予它們的值以下字段一個bean類。

public class authenticationModel { 


    private String dbURL; 
    private String userN; 
    private String userP; 
    private String JDBC_DRIVER; 

需要依賴關係的類如下;

public class login extends HttpServlet { 
@Autowired 
@Qualifier(value="authentication") 
authenticationModel aModel; 

我是相當新的春天,所以我不知道我在做什麼錯或失蹤。

+1

1.你不尊重的Java命名約定; 2.您不認爲錯誤消息和堆棧跟蹤有助於瞭解錯誤是什麼。我的猜測是你得到一個NullPointerException,因爲一個servlet不是Spring組件,因此Spring不能自動調用它們的屬性。使用Spring MVC。並且不要使用已經過時多年的Spring 2.5。 –

回答

0

作爲一個建議,你可以用一個大寫字母命名你的類,例如,而不是authenticationModel命名爲AuthenticationModel。

現在,如果要在特定的Java類中自動裝入Spring Bean,則需要將該類標記爲@Controller或@Service Bean類型。只有春豆才能自動裝載其他豆類。

就你而言,你的Login類沒有被標記爲特定的Spring bean,所以你可能需要使用其中一個註解。

例如:

@Service 
public class LoginService { 
    @Autowired 
    @Qualifier(value="authentication") 
    AuthenticationModel aModel; 
}