使用注解开发


8、使用注解开发

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

使用注解需要导入contex的约束

<?xml version="1.0" encoding="UTF-8"?>


    



8.1 bean

需要在配置中加入< context:component-scan>标签。有了< context:component-scan>,另一个< context:annotation-config/>标签可以移除掉,因为已经被包含进去了。

 
 

@Component注解

//@Component 注解
//等价于 
@Component
public class User {  
     public String name ="xy";
}

8.2 属性注入 @value

@Component
public class User { 
    //相当于 
    @value("xy") 
    public String name; 
    
    //也可以放在set方法上面
    //@value("xy")
    public void setName(String name) { 
        this.name = name; 
    }
}

8.3 衍生的注解

@Component有几个和它具有相同功能的衍生注解,会按照web开发中,mvc架构中分层。

  • dao (@Repository)
  • service(@Service)
  • controller(@Controller)

这四个注解的功能是一样的,都是代表将某个类注册到容器中


8.4 自动装配注解

@Autowired(与@Qualifier搭配使用):默认是byType方式,如果匹配不上,就会byName

@Nullable:字段标记了这个注解,说明该字段可以为空

@Resource:默认是byName方式,如果匹配不上,就会byType


8.5 作用域@scope

//原型模式prototype,单例模式singleton
//scope("prototype")相当于
@Component 
@scope("prototype")
public class User { 
    
    //相当于 
    @value("xy") 
    public String name; 
    
    //也可以放在set方法上面
    @value("xy")
    public void setName(String name) { 
        this.name = name; 
    }
}

关于作用域的知识,回顾 [Bean作用域](##6.4 Bean作用域)


8.6 小结

xml与注解:

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

最佳实践:

  • xml用来管理bean
  • 注解只用来完成属性的注入
  • 要开启注解支持

相关