【Spring】(八)Spring注解开发

Spring注解开发

  • 在Spring4之后,要使用注解开发,必须要保证导入了aop的包

  • 使用注解需要导入context约束,增加注解的支持。

    <?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
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">
    
        <context:annotation-config/>
    
    </beans>
    

1.属性如何注入

  • 1.applicationContext.xml内

    <!--指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="pojo"/>
    
  • 2.User(用@Component代替配置文件中bean的注册)

    //等价于<bean id="user" class="pojo.User" />
    @Component
    public class User {
        public String name="musecho";
    }
    
  • 修改User内属性(用@Value代替配置文件中bean的简单属性值的注入,复杂的属性如map、set等还是用配置文件方便)

    @Value也可以放到set方法上

    @Component
    public class User {
    
        //相当于<property name="name" value="muse"/>
        @Value("muse")
        public String name;
    }
    

2.衍生的注解

  • @Component有几个注解,在web开发中,会按照mvc三层架构分层。

    • dao【@Repository】

    • service【@Service】

    • controller【@Controller】

      这四个注解功能一样,都是代表将某个类注册到Spring中,装备bean


4.自动装配

- @Autowired:自动装配通过类型、名字
	如果Autowired不能唯一自动装配属性,需要通过@Quarifier(value="xxx")
- @Nullable:字段标记了这个注解,说明这个字段可以为null
- @Resource:自动装配通过名字、类型

5.作用域

  • @Scope("xxx")

    @Component
    @Scope(value = "singleton")
    public class User {
    	...
    }
    

6.小结

  • 1.xml与注解:

    • xml更加万能,适用于任何场景。维护简单方便
    • 注解 不是自己类使用不了。维护相对复杂。
  • xml与注解最佳实践:

    • xml用来管理bean;

    • 注解只负责属性的注入

    • 在使用过程中,要注意:要让注解生效,需要开启注解的支持

      <!--指定要扫描的包,这个包下的注解就会生效-->
      <context:component-scan base-package="*"/>
      <context:annotation-config/>
      
posted @ 2021-01-23 21:55  musecho  阅读(66)  评论(0)    收藏  举报