IOC注解

作者: kevin5979 | 来源:发表于2020-11-07 12:59 被阅读0次

导入新的配置文件

  • 我们在编写spring配置文件时,所有的配置都写到一个文件中,不利于维护,这时,可以将配置文件拆成几个对应的模块,再统一导入
image.png
  <!-- 在spring-context中统一导入 -->
  <import resource="spring-context-user.xml"/>
  <import resource="spring-context-student.xml"/>

IOC注解入门

image.png
配置文件代码
// 接口 UserService
package cn.wj.service;
public interface UserService {
  void sayHello();
}

// 实现类 UserServiceImpl
package cn.wj.service;
public class UserServiceImpl implements UserService {
  public void sayHello() {
    System.out.println("Hello IOC 注解!!!");
  }
}

// 配置文件 
<bean id="us" class="cn.wj.service.UserServiceImpl" />
    
// 测试类
@Test
public void testSpringFactory() {
    // 加载配置文件
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
    //获取对象
    UserService userService = (UserService) context.getBean("us");
    // 调用方法
    userService.sayHello();
}

// 结果
Hello IOC 注解!!!

注解简单入门代码
// 接口
...

// 实现类
package cn.wj.service;
import org.springframework.stereotype.Component;
/**
 * <bean id="us" class="cn.wj.service.UserServiceImpl" />
 * @Component : 把当前类交给IOC容器管理
 * 如果没有指定名称, id默认使用类名, 首字母小写 (userServiceImpl)
 */
// @Component   // 参数没写  == @Component(value = "userServiceImpl")
// @Component(value = "us")
@Component("us")
public class UserServiceImpl implements UserService {
  public void sayHello() {
    System.out.println("Hello IOC 注解!!!");
  }
}

// 配置文件
<?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 https://www.springframework.org/schema/context/spring-context.xsd">

// 添加 context标签的名称空间, IDEA自动导入了
+  xmlns:context="http://www.springframework.org/schema/context"

-  <bean id="us" class="cn.wj.service.UserServiceImpl" />  // 不需要配置

/**
base-package: 包的范围
"cn.wj": 相当于扫描cn.wj.所有包下所有的类
*/
+  <context:component-scan base-package="cn.wj" />  // 开启注解扫描

// 测试类
...

// 结果
Hello IOC 注解!!!

IOC常用的注解

bean管理类常用的4个注解(作用相同,推荐使用在不同分层上)
  • @Component 普通的类
  • @Controller 表现层
  • @Service 业务层
  • @Repository 持久层

依赖注入常用的注解
  • **@Value ** 注入普通类型
  • @Autowired 默认按类型进行自动装配(引用类型)
  • @Qualififier 和@Autowired一起使用,使用名称注入
  • @Resource 使用name属性,按名称注入

配置文件依赖注入

// 实体类 Person
public class Person {
  private String name;
  private Integer age;
  private Set Books;
  private Address address;
  // Getter / Setter
  // toString();
}

// 实体类 Address
public class Address {
  private String id;
  private String city;
  // Getter / Setter
  // toString();
}


// 配置文件
<bean id="addr" class="cn.wj.entity.Address">
  <property name="id" value="1"/>
  <property name="city" value="zj"/>
</bean>

<bean id="person" class="cn.wj.entity.Person">
  <property name="name" value="kevin" />
  <property name="age" value="18" />
  <property name="books">
    <set>
      <value>河流</value>
      <value>雾都孤儿</value>
      <value>双城记</value>
    </set>
  </property>
  <property name="address" ref="addr"/>
</bean>

// 测试
@Test
public void testPerson() {
  ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
  Person person = (Person) context.getBean("person");
  System.out.println(person);
}

// 结果
Person{ 
 name='kevin',
 age=18,
 Books=[河流, 雾都孤儿, 双城记],
 address=Address{id='1', city='zj'}
}

利用注解依赖注入

// 实体类 Person
@Component
public class Person {
  @Value(value = "kevin")
  private String name;
    
  @Value(value = "18")
  private Integer age;
    
  @Value(value = "#{'河流,雾都孤儿,双城记'.split(',')}")   // #{表达式}
  private Set Books;
    
  // 1.自动装配(推荐), 不需要给id值, 即无所谓Address类中的id值是什么
  @Autowired
  // 2.Qualifier 按id名称注入, 必须与 Autowired 联合使用才有效果
  @Qualifier(value="addr")
  // 3.Resource相当于 Autowired + Qualifier,  注意 name="addr", 不能省略
  @Resource(name="addr")
  private Address address;
    
  - Getter / Setter // 不需要Setter
  // toString();
}

// 实体类 Address
@Component("attr")
public class Address {
  @Value("1")
  private String id;
    
  @Value("zj")
  private String city;
    
  - Getter / Setter  // 不需要Setter
  // toString();
}


// 配置文件
+ <context:component-scan base-package="cn.wj" />
    
- <bean id="addr" class="cn.wj.entity.Address">...</bean>
- <bean id="person" class="cn.wj.entity.Person">...</bean>

// 测试
同上

// 结果
同上

对象生命周期(作用范围)注解
  • @Scope 生命周期(作用范围)注解,取值singleton(默认值,单实例)和prototype(多实例)
    • 单实例:整个IOC容器只会存在一个实例
    • 多实例:每次都创建一个新的实例对象
@Scope("singleton")  // 单实例
@Component
public class Person {...}

初始化方法和销毁方法注解
  • @PostConstruct 相当于 init-method 实例创建时调用方法
  • @PreDestroy 相当于destroy-method 实例销毁时调用方法
    • 单例下IOC容器销毁,调用方法
    • 多例下java虚拟机负责销毁
@PostConstruct
private void init(){
  System.out.println("init...");
}

@PreDestroy
private void destroy(){
  System.out.println("destroy...");
}

IOC纯注解的方式

纯注解的目的是替换掉所有的配置文件。但是需要编写配置类。

简单演示
package cn.wj.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration  // 声明当前类是配置类
@ComponentScan(value = "cn.wj")   // 开启注解扫描
@Import(value = SpringConfig2.class)    // 导入另一个配置类
public class SpringConfig {

  @Bean("user")  // 将user对象直接注入IOC容器, id为 user
  public User createUser(){
    User user = new User();
    user.setName = "kevin";
    user.setAge = 18;
    return user;
  }

}
image.png
配置类常用注解总结
  • @Confifiguration 声明当前类是配置类

  • @ComponentScan 扫描注解的范围

    • 多个值时:

      @ComponentScan(value = {"cn.wj.demo1","cn.wj.demo2"})   // 只扫描demo1和demo2包下的所有包和类
      
  • @Import 用于导入其他配置类

    • 多个值时:

       @Import(value = {xxx1.class,xxx2.class})    // 导入多个配置类
      
  • @Bean 把当前方法中的返回值对象直接存到IOC容器中

相关文章

  • 2019-08-10 spring

    spring 概述和基于 xml 的 ioc 配置基于注解的 ioc 和 ioc 案例基于注解的 ioc 和 ao...

  • spring基于注解的ioc

    spring基于注解的ioc 教学内容 Spring中的ioc常用注解 案例使用xml和注解方式实现单标的CRUD...

  • Spring框架的IOC功能之注解

    Spring框架的IOC功能之注解的方式 Spring框架的IOC之注解方式的快速入门 步骤一:导入注解开发所有需...

  • 九、使用注解实现IOC的配置

    一、本课目标 掌握使用注解实现IOC的方法 二、使用注解实现IOC 2.1准备工作 注解方式将Bean的定义信息和...

  • 0101-ioc

    背景 ioc是spring的基础,即控制反转。springboot基于注解使用ioc. ioc spring称所有...

  • Spring AOP编程实战

    Spring框架的IOC功能之注解的方式 Spring框架的IOC之注解方式的快速入门 Spring框架中Bean...

  • Spring IoC 容器装配 Bean

    以注解的方式装配 Bean 到 Spring IoC 容器中 使用一个基于注解的方式的 IoC 容器:Annota...

  • IOC注解

    导入新的配置文件 我们在编写spring配置文件时,所有的配置都写到一个文件中,不利于维护,这时,可以将配置文件拆...

  • springBoot项目相关注解

    springBoot项目相关注解 spring相关注解 IoC相关注解 @Component: 类似于 , 没有实...

  • spring-ioc 注解

    spring-ioc 注解使用 配置扫描路径 添加注解 @Component("user") 使用 Spring ...

网友评论

      本文标题:IOC注解

      本文链接:https://www.haomeiwen.com/subject/ggsovktx.html