使用spring注解——定义bean和自动注入
本文内容纲要:使用spring注解——定义bean和自动注入
对于java bean的定义和依赖配置,使用xml文件真心是不方便。
今天学习如何用注解,解决bean的定义和注入。
常用注解:
1、自动注入:@Resources,@Autowired
2、Bean定义:@Component、@Repository、@Service 和 @Constroller
@Component是个泛化概念,可以用在任何层次。如果是web开发,尽量用@Repository、@Service 和 @Constroller
Demo:
以丁磊养猪为例,Pig和DingLei两个类
1、Pig类,以@Component定义为bean
@Componentpublic class Pig {
    private Double weight;
    private String color;
    public Pig(){
        this.weight = 55.8;
        this.color = "black";
    }
    public Double getWeight() {
        return weight;
    }
    public void setWeight(Double weight) {
        this.weight = weight;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public String toString(){
        return  weight + " kg " + color + " pig!";
    }
}
View Code
2、DingLei类,以@Component定义为bean,同时用@Autowired注入依赖pig
@Componentpublic class DingLei {
    @Autowired
    private Pig pig;
    public Pig getPig() {
        return pig;
    }
    public void setPig(Pig pig) {
        this.pig = pig;
    }
    public String toString(){
        return "Dinglei has a " + pig.toString();
    }
}
View Code
3、bean.xml文件中,配置包扫描,注解才生效
context:annotation-config/ :启用注释驱动自动注入
context:component-scan/:对类包进行扫描以实施注释驱动 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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context  
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">
       <!-- <context:annotation-config/> -->
       <context:component-scan base-package="anotation"/>
</beans>
View Code
4、测试类
public class TestAnotation {    @SuppressWarnings("resource")
    public static void main(String[] arg) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        DingLei dingLei = (DingLei) context.getBean("dingLei");
        System.out.println( dingLei.toString() );        
    }
}
View Code
5、运行测试类,可以看到输出。说明注解成功定义bean,并成功完成注入
信息: Loading XML bean definitions from class path resource [bean.xml]Dinglei has a 55.8 kg black pig!
参考:
谢谢无私分享的伙伴,写的非常详细的一篇:Spring注解详解
本文内容总结:使用spring注解——定义bean和自动注入
原文链接:https://www.cnblogs.com/dannyyao/p/6644225.html
以上是 使用spring注解——定义bean和自动注入 的全部内容, 来源链接: utcz.com/z/362330.html
