spring——使用注解开发

注意:spring4之后,使用注解开发需要导入AOP包org.springframework:spring-aop:5.2.5.RELEASE以及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. bean的实现

    (1).指定注解扫描包:<context:component-scan base-package="com.guan.bean"/>

    解释:通过该标签,可以指定要扫描的包且更根据对应的注解执行相应的动作.可以说扫描是为了执行注解

    (2).@Component注解:可以用于将对应的类配置为bean.相当于<bean id="people" class="com.guan.bean.People"/>

  2. 属性如何注入

    (1).使用@Value注解

  3. @Component衍生的注解

    (1).@Component 有多个衍生注解,我们在web开发中,会按照mvc三层架构分层

    • dao -> @Repository
    • service -> @Service
    • controller -> @Controller
  4. 自动装配置

    (1).Autowird

    (2).Nullable

    (3):Resource

  5. 作用域

    (1).主要使用@Scope注解

  6. 小结

    xml与注解使用:

    (1).xml配置:适用范围广,维护简单

    (2).注解配置:使用简单,维护相对复杂

    最佳实践:

    (1).xml用来管理bean

    (2).注解只复杂完成属性的注入

    (3).我们在使用的过程中,只需要注意一个问题:必须让注解生效,需要开启注解的支持

原文地址:https://www.cnblogs.com/Arno-vc/p/13393360.html