使用注解开发

拜拜、爱过 提交于 2020-01-15 17:47:40

使用注解开发

  • 使用注解所需要的包: org.springframework:spring-aop:5.2.2.RELEASE

  • 添加注解的支持

    <?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

    //放在类上,等价于注册了<bean id="user" class="cn.pinked.pojo.User"/>
    @Component
    public class User {
        public String name;
    }
  2. 属性的注入

    //相当于<property name="name" value="大头儿子"/>
    @Value("大头儿子")
    public void setName(String name) {
        this.name = name;
    }
  3. 衍生的注解

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

    • dao -- @Repository
    • service -- @Service
    • controller -- @Controller

    它们的功能都是一样的

  4. 自动装配

    @Autowired

  5. 作用域

    @Scope("")

  6. 小结

    xml与注解

    • xml更加万能,适用于任何场合,维护方便
    • 注解不是自己的类使用不了,维护相对复杂

    最佳实践:

    • xml负责管理bean
    • 注解负责属性的注入
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!