Spring开启自动装配及注解开发

1:开启自动装配

<!--    开启自动装配 就是可以使用@Autowired,不能使用@component,@service,@Repository等注解-->
    <context:annotation-config/>

2: 开启自动装配并扫描指定包【建议使用,可以少扫描其他不必要的类】

<!--    开启自动装配,扫描指定包,这里可以使用@component,@service,@Repository等注解 替代了 <context:annotation-config/>-->
    <context:component-scan base-package="org.example"/>

3:注解使用

@Repository   //作用在类上,表示数据层,此类的对象创建交由Spring管理
 @Service      //作用在类上,表示Service层,此类的对象创建交由Spring管理
 @Controller   //作用在类上,表示Controller,此类的对象创建交由Spring管理
 @Component    //作用在类上,表示普通层=类 ,此类的对象创建交由Spring管理

 @Value        //作用在属性上,此类创建对象时,当前属性的初始值
 
 @Resource     //作用在对象属性上,给当前属性赋值,根据对象名称查找对象赋值给当前对象属性【此注解不属于Spring,属于java拓展包<!--    @Resource注解 -->javax.annotation-api】
 @Autowired    //作用在对象属性上,给当前属性赋值,在Spring根据类型查找,相同类型对象赋值
 @Qualifier("对象名") //作用在对象属性上,一般用于和@Autowired配合使用,当@Autowired在Spring容器中发现两个和当前属性对象相同的时候,使用此注解,根据对象名称来赋值
经验分享 程序员 微信小程序 职场和发展