关于spring:Spring使用注解开发

6次阅读

共计 1162 个字符,预计需要花费 3 分钟才能阅读完成。

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

    <!-- 指定要扫描的包,这个包下的注解就会失效 -->
    <context:component-scan base-package="com.sunfl.pojo"/>
    <context:annotation-config/>

</beans>
  1. bean
  2. 属性如何注入

    // 等价于 <bean id="user" class="com.sunfl.pojo.User"/>
    @Component
    public class User {
    
     public String name;
    
     // 相当于 <property name="name" value="向日葵">
     @Value("向日葵")
     public void setName(String name) {this.name = name;}
    }
  3. 衍生的注解
    @Component 有几个衍生注解,咱们在 web 开发中,会依照 mvc 三层架构分层

    • dao【@Repository】
    • service【@Service】
    • controller【@Controller】

    这四个注解性能都是一样的,都是代表将某个类注册到 Spring 容器中,拆卸 Bean

  4. 主动装配置

    • @Autowired: 主动拆卸通过类型、名字
    • @Nullable: 字段标记了这个注解,阐明这个字段能够为 null
    • @Resource: 主动拆卸通过类型、名字
  5. 作用域

    @Component
    @Scope("prototype")
    public class User {}
  6. 小结
    xml 与注解比照:

    • xml 更加万能,实用于任何场合!保护简略不便
    • 注解 不是本人类应用不了,保护绝对简单

    最佳实际:

    • xml 用来治理 bean
    • 注解只负责实现属性的注入
正文完
 0