如何在春天自动装配属性
问题描述:
我想通过在我的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;
我是相当新的春天,所以我不知道我在做什么错或失踪。
答
作为一个建议,你可以用一个大写字母命名你的类,例如,而不是authenticationModel命名为AuthenticationModel。
现在,如果要在特定的Java类中自动装入Spring Bean,则需要将该类标记为@Controller或@Service Bean类型。只有春豆才能自动装载其他豆类。
就你而言,你的Login类没有被标记为特定的Spring bean,所以你可能需要使用其中一个注解。
例如:
@Service
public class LoginService {
@Autowired
@Qualifier(value="authentication")
AuthenticationModel aModel;
}
1.你不尊重的Java命名约定; 2.您不认为错误消息和堆栈跟踪有助于了解错误是什么。我的猜测是你得到一个NullPointerException,因为一个servlet不是Spring组件,因此Spring不能自动调用它们的属性。使用Spring MVC。并且不要使用已经过时多年的Spring 2.5。 –