spring IOC 常用注解一(简单类型数据装配及其他Bean的引用)详解

前言: 有粉丝评论我之前的博客文字太少了,打算从这篇博客开始多增加一些文字内容的介绍,欢迎各位粉丝提建议,博主更加努力写博客,为了让大家可以拿去解决一些问题,欢迎各位一起讨论,共同进步早日进大公司,加油!加油!

*spring四个常用注解用户装配Bean

一:@Component 此注解使用在class上来声明一个Spring组件(Bean), 将其加入到应用上下文中 ,添加到IOC容器中,不区分组件类型。

二:@Controller 此注解表示Action层的组件,用在Action层,在类上添加,目的是将Action的实现类添加到IOC容器中,是@Component注解的一种具体形式。

三:@Service 此注解表示Service(业务)层组件,在class类上添加表示是一个业务类执行一些业务逻辑等, 目的是将Service层的实现类添加到IOC容器中,是@Component注解的一种具体形式。

四:@Repositor 此注解表示Dao层组件 在Dao层实现类上面添加用于访问数据库,目的是将Dao的实现类添加到IOC容器中。

**spring四个常用注解属性注入

一:@Value 此注解使用在字段、构造器参数和方法参数上。@Value可以指定属性取值的表达式,支持通过#{}使用SpringEL来取值,也支持使用${}来将属性来源中(Properties文件、本地环境变量、系统属性等)的值注入到bean的属性中,它用来注入基本数据类型,不能注入引用数据类新。
二:@Resource 集合的数据装配 使用的是@Resource 默认是按Byname进行数据装配。
三:@Autowired 使用的是spring提供的 数据装配,默认是ByType匹配 当存在多个同名Bean的时候是ByName匹配,
此注解用于其他bean的引用、setter方法以及构造方法上,显式地声明依赖。根据ByType匹配来自动注入。
当在其他Bean引用上使用此注解,并且使用属性来传递值时,Spring会自动把值赋给此field。也可以将此注解用于私有属性(不推荐),如下。

@Component
public class User {
    @Autowired
    private Customer custoemr;
}

最经常的用法是将此注解用于settter上,这样可以在setter方法中添加自定义代码。如下:


@Component
public class User {
   private Customer customer;
    
   @AutoWired
   public setCustomer(Customer customer) {
      this.customer = customer;
   }
}

在构造方法上使用@Autowired注解的时候,需要注意的一点就是一个类中只允许有一个构造方法使用此注解。
此外,在Spring4.3后,如果一个类仅仅只有一个构造方法,即使不使用此注解,那么Spring也会自动注入相关的bean在IOC容器中。如下:

@Component
public class User {
   private Customer customer;
   
   public setCustomer(Customer customer) {
      this.customer = customer;
   }
}
<!--在IOC容器中会自动的注入Bean-->
<bean id="user" class="com.aliwo.user"/>

四:@Qualifier 此注解是和@Autowired一起使用的。使用此注解可以让你对注入的过程有更多的控制。
@Qualifier可以被用在单个构造器或者方法的参数上。当上下文有几个相同类型的bean, 使用@Autowired则无法区分要绑定的bean,此时可以使用@Qualifier来指定名称 如下:

@Component
public class User {
    @Autowired
    @Qualifier("customer1")
   private Customer customer;
}

一个作用范围的注解

@Scope:用于指定bean的作用域,一般就是singleton(单例)和prototype(非单例)

一个实例化时机的注解

@Lazy:懒加载 实例化的时候加载 单例的

两个生命周期的注解

@PostConstruct 初始化方法相当于 init-method=""

@PostConstruct
public void init() {
    System.out.println("初始化方法");
}                    

@PreDestroy 销毁方法相当于 destroy-method=" "

@PreDestroy
public void destroy(){
    System.out.println("销毁方法");
}

***简单数据类型的装配

使用maven搭建的项目:项目目录如下:
在这里插入图片描述
第一步扫描包这个是使用注解(组件)的前提添加在spring.xml文件中引入<context:component-scan base-package=""/>命名空间
配值spring.xml配置文件:

<?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="annotation01.entity"/>
    
    <!--数据装配,读取配置文件的一种方式-->
    <!--<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:info.properties"/>
    </bean>-->
    
     <!--数据装配,读取配置文件的二种方式,基于命名空间的读取配置文件,在实际开发中推荐使用-->
    <context:property-placeholder location="info.properties"/>

    <bean id="cu" class="annotation01.entity.Customer">
        <property name="username" value="xuyayuan"/>
        <property name="sex" value="man"/>
    </bean>
    
</beans>

上面配置中读取配置文件的配置 在resources资源根目录下配置info.properties文件

jdbc.username=admin
password=admins

书写使用注解的实体类简单数据类型

package annotation01.entity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.*;

/**
 * package_name:annotation01.entity
 *
 * @author:徐亚远 Date:2020/2/20 16:56
 * 项目名:springDemo01
 * Description:TODO
 * Version: 1.0
 **/
//默认 Bean的名字id为类的首字母小写
//@Component("us")
@Component
//懒加载 实例化的时候加载 单例的
//@Lazy
//作用域表明非单例的
@Scope("prototype")
public class User {
    /**
     * 简单数据类型的数据
     */
    @Value("${jdbc.username}")
    private String username;
    @Value("${password}")
    private String password;
    @Value("22")
    private Integer num;
    @Value("true")
    private Boolean flag;
    /**其他Bean的引用*/
    /**
     * @Autowired 方式一:使用的是spring提供的
     * 数据装配
     * 默认是ByType匹配 当存在多个同名Bean的时候是ByName匹配
     * 结合 @Qualifier("cu")指定特定的名字
     * 方式二: 使用@Resource 是javaEE提供的用法和@Autowired用法一样
     */
   /* @Autowired
    @Qualifier("cu")*/
    @Resource
    private Customer customer;


    /**构造方法*/
    public User() {
    }

    /**
     * 初始化方法
     * @PostConstruct 相当于 init-method=""
     */
    @PostConstruct
    public void init() {
        System.out.println("初始化方法");
    }
    /**
     * 销毁方法
     * @PreDestroy 相当于 destroy-method=""
     */
    @PreDestroy
    public void destroy(){
        System.out.println("销毁方法");
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", num=" + num +
                ", flag=" + flag +
                ", customer=" + customer +
                '}';
    }
}

其他Bean的引用实体类Customer类

package annotation01.entity;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

/**
 * package_name:annotation01.entity
 *
 * @author:徐亚远 Date:2020/2/20 17:52
 * 项目名:springDemo01
 * Description:TODO
 * Version: 1.0
 **/
@Component
public class Customer {

    @Value("customer")
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Value("woman")
    private String sex;

    @Override
    public String toString() {
        return "Customer{" +
                "username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

配置测试类

package annotation01.controller;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * package_name:annotation01.controller
 *
 * @author:徐亚远 Date:2020/2/20 16:56
 * 项目名:springDemo01
 * Description:TODO
 * Version: 1.0
 **/

public class UserController {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("annotation01/spring.xml");
        System.out.println(ac.getBean("user"));
        System.out.println("========");
        System.out.println(ac.getBean("customer"));
        //ac.destroy();
        System.out.println(ac.getBean("user")==ac.getBean("user"));
    }
}

运行结果如图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值