【Java】Spring中 bean方式注册组件

前言

     小编最近在深入学习关于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);
    }

}

小结

    通过两种方式,我们可以看出,使用注解可以明确地指出有哪些组件,哪个范围的组件被注册,而使用配置文件,也能够起到同样的效果,但是使用注解的方式看起来简洁,方便。

                                                                           感谢您的访问!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值