标签:自动化 autowire wan more 称多 etc ret work beans
title: spring03
date: 2020-03-09 19:06:11
tags:自动装配(autowired)
本部分是自动装配的内容。
摘抄自秦老师
Spring中bean有三种装配机制,分别是:
这里我们主要讲第三种:自动化的装配bean。
Spring的自动装配需要从两个角度来实现,或者说是两个操作:
People
package com.nevesettle.pojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class People {
private String name;
@Autowired
@Qualifier("cat321")
private Cat cat;
@Autowired
private Dog dog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
}
Cat
package com.nevesettle.pojo;
public class Cat {
public void shout(){
System.out.println("miao..");
}
}
Dog
package com.nevesettle.pojo;
public class Dog {
public void shout(){
System.out.println("wang..");
}
}
只需要在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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--此处是开启自动装配的配置-->
<context:annotation-config/>
<bean id="cat321" class="com.nevesettle.pojo.Cat"/>
<bean id="cat323211" class="com.nevesettle.pojo.Cat"/>
<bean id="dog" class="com.nevesettle.pojo.Dog"/>
<bean id="people" class="com.nevesettle.pojo.People"/>
</beans>
@Autowired
@Resource
标签:自动化 autowire wan more 称多 etc ret work beans
原文地址:https://www.cnblogs.com/wuren-best/p/12450455.html