前言
小编最近在深入学习关于Spring的技术知识,这一篇文章主要是来介绍Spring的注解内容,Spring注解注册组件到容器中有以下几种方式。
容器与组件
如图所示,Spring中的容器和组件之间的关系,通俗地理解IOC容器是管理组件关系的,组件是如何添加到容器中的呢?
bean方式注册组件
一、配置文件
<bean>标签代表一个组件,<context>并指明了包扫描的范围。
<?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">
<!--包扫描,标注了@controller @service @Repository @component-->
<context:component-scan base-package="com.atguigu"></context:component-scan>
<bean id="person" class="com.atguigu.bean.Person">
<property name="age" value="18"></property>
<property name="name" value="grace"></property>
</bean>
</beans>
二、注解
@Configuration代表这是一个配置类
@bean 代表这是一个组件
@ComponentScan 指定了包扫描的范围以及过滤的条件
package com.atguigu.config;
import com.atguigu.BookService.BookService;
import com.atguigu.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
/**
* @author 冯浩月
* @version 0.0.3
* @description MainConfig
* @since 2019-04-16 20:30
*/
// 告诉spring这是一个配置类
@Configuration
@ComponentScan(value = "com.atguigu",includeFilters={
@ComponentScan.Filter(type=FilterType.ANNOTATION,classes={Controller.class, Controller.class}),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {BookService.class}),
@ComponentScan.Filter(type = FilterType.CUSTOM,classes = {MyTypeFilter.class})
},useDefaultFilters = false)
public class MainConfig {
// 告诉spring这是一个bean,类型为返回值的类型
@Bean("person")
public Person person(){
return new Person("grace",24);
}
}
小结
通过两种方式,我们可以看出,使用注解可以明确地指出有哪些组件,哪个范围的组件被注册,而使用配置文件,也能够起到同样的效果,但是使用注解的方式看起来简洁,方便。
感谢您的访问!