Spring:IOC容器的依赖注入(DI)之注解开发

郎家岭伯爵 2022年01月21日 688次浏览

前言

关于IOC容器的依赖注入之前已写过两篇博文:

而本文意在补充记录开发过程中IOC容器常用的其它几个注解。

实现

@Component注解

作用:

  • 组件,作用在类上。说明这个类被Spring管理,即:Bean。
  • 等价于在beans.xml中配置等价于 <bean id="user" class="com.langjialing.pojo.User"/>

导入依赖

需要在pom.xml文件中导入spring-context依赖。

spring-context的dependency引入:

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-context</artifactId>
  4. <version>5.3.13</version>
  5. </dependency>

配置beans.xml文件

作用:

  • 启用注解:<context:annotation-config/>
  • 指定@Component注解所作用的包的路径:<context:component-scan base-package="com.langjialing.pojo"/>
  • 此文件名建议命名为applicationContext.xml。本文为了与前两篇博文相呼应,因此命名为beans.xml

完整的beans.xml文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. https://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context
  8. https://www.springframework.org/schema/context/spring-context.xsd">

  9. <context:annotation-config/>
  10. <context:component-scan base-package="com.langjialing.pojo"/>

  11. <!-- <bean id="user" class="com.langjialing.pojo.User"/> -->
  12. </beans>

pojo:User.java

  1. package com.langjialing.pojo;


  2. import org.springframework.stereotype.Component;

  3. //等价于 <bean id="user" class="com.langjialing.pojo.User"/>
  4. //@Component:组件,作用在类上。说明这个类被Spring管理,即:Bean。
  5. @Component
  6. public class User {
  7. public String name = "langjialing";
  8. }

编写测试类

  1. import com.langjialing.pojo.User;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;

  5. public class MyTest {
  6. @Test
  7. public void test1(){
  8. ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
  9. User user = context.getBean("user", User.class);

  10. System.out.println(user.name);
  11. }
  12. }

测试结果

测试结果

当前目录结构

当前目录结构

当前目录结构

@Value注解

作用:

  • 注入属性值。
  • 等价于<bean id="user" class="com.langjialing.pojo.User"> <property name="name" value="langjialing"/> </bean>。此处注意使用property属性的话需要User.java类中有对应的setter方法。
  • 适用于属性值较少的情况。当属性值较多时仍然推荐使用beans.xml配置文件

pojo中User.java修改

@Value注解

@Value注解

测试结果

@Value注解测试截图

@Value注解测试截图

@Component衍生出的注解

注:

  • @Component注解有几个衍生注解,在Web开发中,会按照MVC三层架构分层,因此所对应的有三个@Component衍生出的注解。
  • 衍生出的注解与@Component注解的功能是完全一致的,都是代表将类注册到Spring中,即:装配Bean。
  • 衍生出的注解意在更好地区分MVC三层结构。

修改beans.xml

注:

  • 本章节需要修改beans.xml文件中的 context:component-scan base-package 标签,意在指定扫描包的路径。否则下文中的Bean无法成功注入。

指定 component-scan 的路径

指定 component-scan 的路径

@Repository:用于Dao层

@Repository

@Repository

@Service:用于Service层

@Service

@Service

@Controller:用于Controller层

@Controller

@Controller