(四)Spring 的 bean 管理(注解方式)

目录


前言

注解可以写在 方法属性 上 ;

使用 注解,需要导入 aop 包;

使用 注解,不代表,我们可以完全脱离配置文件,还是需要配置文件的,只是配置文件中,不再需要写很多配置 ;


使用 aop 的配置文件写法

相对于使用纯配置文件的 bean 约束,使用aop,多了一个 context 约束

多加一个 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" 

    <!--多了一个 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"> <!-- bean definitions here -->


</beans>

开启注解扫描

在配置文件中加上一句配置 ,仅仅需要写这一句配置。

它会去包所在路径,扫描里面的 方法属性 上 ,是否有注解,

 <!--开启注解扫描-->
    <context:component-scan base-package="包名"></context:component-scan>

base-package 属性,写上要扫描的包路径;

  • 有多个包需要扫描的时候

    比如:现在有2个包:ijava.xin.aop、ijava.xin.ioc,需要扫描

    • 我们可以在属性里面用 逗号 隔开:
     <context:component-scan base-package="ijava.xin.aop、ijava.xin.ioc">
     </context:component-scan>

    这样写是一种写法,但是当有十几个、几十个包需要扫描的时候,就显得ZZ了 ;

    • 写上级的包名。

    比如:ijava.xin.aop、ijava.xin.ioc,它们都属于 ijava.xin 下面的,我们就可以在属性里面填上 ijava.xin ,这样就扫描 ijava.xin 下面所有的子包了。

     <context:component-scan base-package="ijava.xin">
     </context:component-scan>

利用注解创建对象

  1. Spring 建议我们使用其他的三个标签创建对象:

    @Component(value = "user")
    public class User {
    
    public void add(){
        System.out.println("User add ...");
    }
    }

    使用 @Component 创建对象,属性有 value 跟 使用配置文件的 bean 标签的 id 一样的作用;value 可以省略不写 ;

    @Controller() : WEB层使用
    @Service()   : 业务层使用
    @Repository() : 持久层使用

    当前 Spring 版本(4.X),@Component 标签功能跟那三个是一样的,但是,我们还是应该分开使用,在哪一层就是有对应的标签;Spring 会在后续的版本,对它们进行功能的增强 ;

  2. scope 对应的 @Scope

    @Component(value = "user")
    @Scope(value = "prototype")
    public class User {
    
    public void add(){
        System.out.println("User add ...");
    }
    }

    使用多例,创建对象 ;@Scope 默认值也是 singleton


注解方式注入属性

使用注解注入的时候,不需要写 set 方法 ;

  1. @Autowired

    @org.springframework.stereotype.Service("service")
    public class Service {
    
    @Autowired
    private UserDao userDao ;
    
    public void add(){
        System.out.println("Service add ...");
        userDao.add();
    }
    }

    使用 @Autowired 注解,就可以自动填充属性 ;

    @Autowired 注解 是如何找到对象,并且注入的呢?

    当属性被标上 @Autowired 注解 的时候,它会根据类的类型,去寻找该类型的对象,跟类上的创建对象注解的内容没有关系 ;


  2. @Resource

    @org.springframework.stereotype.Service("service")
    public class Service {
    
    @Resource(name = "userDao")
    private UserDao userDao ;
    
    public void add(){
        System.out.println("Service add ...");
        userDao.add();
    }
    }

    使用 @Resource 注解,则根据注解的内容提供的名字,去寻找对应的对象 ;


配置文件和注解混合使用

  1. 创建对象使用配置文件方式实现
  2. 注入属性,使用注解方式实现
原文地址:https://www.cnblogs.com/young-youth/p/11665689.html