zoukankan      html  css  js  c++  java
  • Spring 面向注解开发

    8. 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:component-scan base-package="com.peng.pojo"/>
        <context:annotation-config/>
    </beans>
    
    1. bean

      //等价于 <bean id="user" class="com.peng.dao.User"/>
      //@Component组件,放在类上,说明这个类被Spring管理了
      @Component
      public class User {
          public String name = "peng";
      }
      
    2. 属性如何注入

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

      也可以放到set上

      @Component
      public class User {
          public String name;
          
          @Value("peng")
          public void setName(String name) {
              this.name = name;
          }
      }
      
    3. 衍生的注解

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

      • dao【@Repository】

        import org.springframework.stereotype.Repository;
        
        @Repository
        public class UserDao {
        }
        
      • service【@Service】

      • controller【@Controller】

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

    4. 自动装配置

      @Autowired、@Nullable、@Resource,前面介绍过

    5. 作用域

      @Scope("singleton") / @Scope("prototype")

    6. 小结 xml 与 注解

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

      xml与注解最佳实践:

      • xml用来管理bean
      • 注解只负责完成属性的注入
      • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
  • 相关阅读:
    创建自动执行存储过程
    创建链接服务器
    SQLServer查询特殊符号处理
    SQL Server维护计划自动备份数据库
    SQL Server收缩数据库&列出所有表的数据条数
    SQL server日志文件过大处理方式
    SQL Server批量删除数据库表
    done apple经理面 匹配括号但是不能用stack
    done Beaconfire中国小哥中规中矩screening
    done marlabs挺难的screening
  • 原文地址:https://www.cnblogs.com/peng8098/p/java_15.html
Copyright © 2011-2022 走看看