SPring(3)-@autowired
SPring 中一个类中调用另一些bean,一开始是xml格式配置的,后来变的更灵活,用了@autowired。
1.配置文件的方法
2.@autowired方法
例:有三个类,boss office car
1.配置文件的方法
1.1 bean.xml
car 和office 作为 boss 的属性
<?xml version="1.0" encoding="UTF-8" ?>
<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="boss" class="com.baobaotao.Boss">
<property name="car" ref="car"/>
<property name="office" ref="office" />
</bean>
<bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="002"/>
</bean>
<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value=" 红旗 CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>
1.2 调用
public class Boss
{
private Car car;
private Office office;
// 省略 get/setter
@Override
public String toString()
{
return "car:" + car + "/n" + "office:" + office;
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnoIoCTest {
public static void main(String[] args)
{
String[] locations = {"beans.xml"};
ApplicationContext ctx =
new ClassPathXmlApplicationContext(locations);
Boss boss = (Boss) ctx.getBean("boss");
System.out.println(boss);
}
}
2.@autowired方法
boss car office 三个类松耦合,就是没啥关系,灵活装配用了@autowired方法。
2.1 applicationContext.xml 多加一条
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
2.2 bean.xml
三个bean 是独立的
<?xml version="1.0" encoding="UTF-8" ?>
<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">
<!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 -->
<bean class="org.springframework.beans.factory.annotation.
AutowiredAnnotationBeanPostProcessor"/>
<!-- 移除 boss Bean 的属性注入配置的信息 -->
<bean id="boss" class="com.baobaotao.Boss"/>
<bean id="office" class="com.baobaotao.Office">
<property name="officeNo" value="001"/>
</bean>
<bean id="car" class="com.baobaotao.Car" scope="singleton">
<property name="brand" value=" 红旗CA72"/>
<property name="price" value="2000"/>
</bean>
</beans>
2.3JAVA代码 想怎么用,在前面加上关键词 @Autowired
import org.springframework.beans.factory.annotation.Autowired;
public class Boss
{
@Autowired
private Car car;
@Autowired
private Office office;
}
public class Boss
{
private Car car;
private Office office;
@Autowired
public Boss(Car car ,Office office){
this.car = car;
this.office = office ;
}

浙公网安备 33010602011771号