前言
关于IOC容器的依赖注入之前已写过两篇博文:
- IOC容器的依赖注入(DI)之基本实现为完全由beanx.xml文件来注入bean。
- Spring:IOC容器的依赖注入(DI)之自动装配Bean为自动装配bean,简化了beans.xml中的配置项。
而本文意在补充记录开发过程中IOC容器常用的其它几个注解。
实现
@Component注解
作用:
- 组件,作用在类上。说明这个类被Spring管理,即:Bean。
- 等价于在beans.xml中配置
等价于 <bean id="user" class="com.langjialing.pojo.User"/>
。
导入依赖
需要在pom.xml文件中导入spring-context
依赖。
spring-context的dependency引入:
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>5.3.13</version>
- </dependency>
配置beans.xml文件
作用:
- 启用注解:
<context:annotation-config/>
。 - 指定@Component注解所作用的包的路径:
<context:component-scan base-package="com.langjialing.pojo"/>
。 - 此文件名建议命名为
applicationContext.xml
。本文为了与前两篇博文相呼应,因此命名为beans.xml
。
完整的beans.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
- https://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/context
- https://www.springframework.org/schema/context/spring-context.xsd">
- <context:annotation-config/>
- <context:component-scan base-package="com.langjialing.pojo"/>
- <!-- <bean id="user" class="com.langjialing.pojo.User"/> -->
- </beans>
pojo:User.java
- package com.langjialing.pojo;
- import org.springframework.stereotype.Component;
- //等价于 <bean id="user" class="com.langjialing.pojo.User"/>
- //@Component:组件,作用在类上。说明这个类被Spring管理,即:Bean。
- @Component
- public class User {
- public String name = "langjialing";
- }
编写测试类
- import com.langjialing.pojo.User;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class MyTest {
- @Test
- public void test1(){
- ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
- User user = context.getBean("user", User.class);
- System.out.println(user.name);
- }
- }
当前目录结构
@Value注解
作用:
- 注入属性值。
- 等价于
<bean id="user" class="com.langjialing.pojo.User"> <property name="name" value="langjialing"/> </bean>
。此处注意使用property属性的话需要User.java类中有对应的setter方法。 - 适用于属性值较少的情况。当属性值较多时仍然推荐使用beans.xml配置文件。
pojo中User.java修改
测试结果
@Component衍生出的注解
注:
- @Component注解有几个衍生注解,在Web开发中,会按照MVC三层架构分层,因此所对应的有三个@Component衍生出的注解。
- 衍生出的注解与@Component注解的功能是完全一致的,都是代表将类注册到Spring中,即:装配Bean。
- 衍生出的注解意在更好地区分MVC三层结构。
修改beans.xml
注:
- 本章节需要修改beans.xml文件中的
context:component-scan base-package
标签,意在指定扫描包的路径。否则下文中的Bean无法成功注入。