Blueherb In solitude, where we are least alone 王佳鑫

spring心得

属性注入 autowire
1.xml autowire="byName"


点击查看代码
public class User {
    @Value(value = "abc")
    private String name;
    public void add(){
        System.out.println("add....");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    private Cat cat;

    private Dog dog;

    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;
    }
}
因为按byName规则找对应set方法,真正的setCat就会执行,对象初始化,Cat就有值了。 2.注解 @Autowire
点击查看代码
public class User {
    @Value(value = "abc")
    private String name;

    public void add() {
        System.out.println("add....");
    }

    @Autowired
    private Cat cat;
}
@Autowired与@Resource异同: @Autowired 默认byType ,想用 byName @Qualifier联合使用 @Resource 默认byName ,先按name匹配。匹配不上按type

原来我一直用的是属性注入

点击查看代码
@Service
public class Room {

    @Autowired
    private Computer computer;
}

setter注入

点击查看代码
@Service
public class BService {
    AService aService;

    @Autowired
    public void setaService(AService aService) {
        this.aService = aService;
    }
}

构造注入

点击查看代码
@Service
public class AService {
    BService bService;
    @Autowired
    public AService(BService bService) {
        this.bService = bService;
    }
}
posted @ 2022-07-27 10:21  阿呆学习之路  阅读(16)  评论(0编辑  收藏  举报