Spring:使用注解开发

6.使用注解开发

在Spring4之后开发,必须导入aop包

在使用注解必须导入content约束

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

</beans>

包扫描

<!--指定注解扫描包-->
<context:component-scan base-package="com.kuang.pojo"/>
  1. bean

    @component

    @Component("user")
    // 相当于配置文件中 <bean id="user" class="当前注解的类"/>
    public class User {
       public String name = "jack";
    }
    
  2. 属性如何注入

    @Value

    • 属性名上

      @Component("user")
      // 相当于配置文件中 <bean id="user" class="当前注解的类"/>
      public class User {
         @Value("jack")
         // 相当于配置文件中 <property name="name" value="jack"/>
         public String name;
      }
      
    • set方法上

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

    Dao:@Repository

    Service:@Service

    Controller:@Controller**@Component三个衍生注解**

    为了更好的进行分层,Spring可以使用其它三个注解,功能一样,目前使用哪一个功能都一样。

    • @Controller:web层
    • @Service:service层
    • @Repository:dao层

    写上这些注解,就相当于将这个类交给Spring管理装配了!

  4. 自动装配(上面已讲)

    @Autowired

    @Rerouce

    @Qualifier与@Autowired配合使用

  5. 作用域

    @Scope(作用范围)

    @Controller("user")
    @Scope("prototype")
    public class User {
       @Value("jack")
       public String name;
    }
    
  6. 小结

    XML与注解比较

    • XML可以适用任何场景 ,结构清晰,维护方便
    • 注解不是自己提供的类使用不了,开发简单方便

    xml与注解整合开发 :推荐最佳实践

    • xml管理Bean
    • 注解完成属性注入
    • 使用过程中, 可以不用扫描,扫描是为了类上的注解
    <context:annotation-config/>  
    

    作用:

    • 进行注解驱动注册,从而使注解生效
    • 用于激活那些已经在spring容器里注册过的bean上面的注解,也就是显示的向Spring注册
    • 如果不扫描包,就需要手动配置bean
    • 如果不加注解驱动,则注入的值为null!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值