Spring 自动装配
2021-06-07 09:04
标签:demo 代码 private mic 方便 就会 auto sch imp 很明显之前学的方式 手动配置还是不够方便。就需要我们去学习Spring的自动装配! 定义几个简单类 配置文件如下: 使用前提 导入上面配置后 如果配置文件定义类重复想要指定可用下面方法 除了Autowire java也自带一个Resource注解,功能几乎差不多。 Spring 自动装配 标签:demo 代码 private mic 方便 就会 auto sch imp 原文地址:https://www.cnblogs.com/OfflineBoy/p/14587887.htmlautowire="byName"
package Demo;
public class Cat {
public void shout(){
System.out.println("miao~");
}
}
package Demo;
public class Dog {
public void shout(){
System.out.println("wang~");
}
}
package Demo;
public class People {
private Cat cat;
private Dog dog;
private String 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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
autowire="byType"
小结
注解配置(主流方式)
xml配置文件更新成如下@Autowired
上面案例代码可改为package Demo;
import org.springframework.beans.factory.annotation.Autowired;
public class People {
//在此处使用Autowired
@Autowired
//先根据类型匹配,然后根据名字匹配
private Cat cat;
@Autowired
private Dog dog;
private String 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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
小结