IOC注解

2020-11-07  本文已影响0人  kevin5979

导入新的配置文件

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个注解(作用相同,推荐使用在不同分层上)

依赖注入常用的注解

配置文件依赖注入

// 实体类 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")  // 单实例
@Component
public class Person {...}

初始化方法和销毁方法注解
@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
配置类常用注解总结
上一篇 下一篇

猜你喜欢

热点阅读