还没学到注解,这里以xml配置为例子
通过autowire属性为bean定义指定自动装配,且有四种模式:
- no : 不进行自动装配;这里我尝试的应该就是default ,即:
<bean id="people" class="com.henry.POJO.People" autowire="default">
按官网好像可以更改默认情况,但不建议,咱也不会,反正不要自动装配就啥都不加就好。
- byName:根据set方法后面的名字与bean id 匹配 如,如果我在People类设置 setDog1(Dog dog); 而不是 setDog(Dog dog),则我的xml里面 一定要为
<bean id="dog1" class="..."/>
如果,你的bean 配置如上,则你的set方法一定要如下:
public void setDog(Dog dog1) {
this.dog = dog;
}
- byType:byType就避免了以上的尴尬,直接连 bean 的 id 都扔了也可以,直接
<bean class="..."/>
但如果有多个相同类型的bean,则会丢出编译时异常
4.constructor:对于构造器,类似于byType但适用于构造函数参数。如果容器中不存在构造函数参数类型的一个bean,则将引发致命错误。
补充:autowire-candidate属性
可以通过autowire-candidate=“false”来避免被自动装配,如我下面示例的dog。
但是:autowire-candidate属性旨在仅影响基于类型的自动装配。它不会影响按名称的显式引用,即使未将指定的Bean标记为自动装配候选,名称也可以解析。因此,如果按名称匹配,按名称自动装配仍会注入Bean。
以下为我举得例子:
猫🐱
package com.henry.POJO;
public class Cat implements Animal {
public void shout() {
System.out.println("miaomiao~~");
}
}
狗🐕
package com.henry.POJO;
public class Dog implements Animal{
public void shout() {
System.out.println("wangwang!!");
}
}
人🧑
package com.henry.POJO;
public class People implements Animal{
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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private Cat cat;
private Dog dog;
private String name;
public void shout() {
System.out.println("哈哈");
}
@Override
public String toString() {
return "People{" +
"Mycat=" + cat +
", Mydog=" + dog +
", Myname='" + name + '\'' +
'}';
}
}
测试类:
import com.henry.POJO.People;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people = (People) context.getBean("people");
people.getCat().shout();
people.getDog().shout();
System.out.println("name: "+people.getName());
people.shout();
}
}
配置文件:beans.xml
<?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.xsd">
<bean id="cat" class="com.henry.POJO.Cat" autowire-candidate="false"/>
<bean id="dog" class="com.henry.POJO.Dog"/>
<bean id="people" class="com.henry.POJO.People" autowire="byName">
</bean>
</beans>
结果:
autowire-candidate="false"失效
注解@Autowired
自己还没试,先记录一下:
- @Autowired 是默认byType找不到,再byName(好像算退回机制)
- 通过@Qualifier(value = " ? ")可以再多个type bean 的情况下指定一个bean,这样就不会报错了。