要使用@Autowired 得在spring的配置文件里设置:
xmlns:context="http://www.springframework.org/schema/context "
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd ">
使用<context:annotation-config></context:annotation-config>之后就可以在类里设置@Autowired来自动绑定了。
实例如下:
1.配置文件:
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans "
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "
xmlns:context="http://www.springframework.org/schema/context "
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd ">
<context:annotation-config></context:annotation-config>
<bean id="auto123" class="org.michael.spring.demo.autowire.AutoWireBean">
<property name="name1" value="Jordan"></property>
</bean>
<bean id="auto" class="org.michael.spring.demo.autowire.AutoWireBean" autowire-candidate="false">
<property name="name1" value="Crystal"></property>
</bean>
<bean id="autowire1" class="org.michael.spring.demo.autowire.AutoWireBean2" >
<property name="helloWord" value="Michael"></property>
</bean>
</beans>
2.AutoWireBean2
package org.michael.spring.demo.autowire;
import org.springframework.beans.factory.annotation.Autowired;
public class AutoWireBean2 {
private String helloWord;
@Autowired
private AutoWireBean auto;
public String getHelloWord() {
return helloWord;
}
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public AutoWireBean getAuto() {
return auto;
}
}
注意,这里的auto可以不用写set方法
本文介绍如何在Spring中使用@Autowired注解实现依赖注入。通过在配置文件中加入<context:annotation-config>,可以在不编写setter方法的情况下自动装配Bean。文章提供了一个具体的示例,展示了配置文件的设置及带有@Autowired注解的类。

被折叠的 条评论
为什么被折叠?



