随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。

github中的中文文档:

https://github.com/DocsHome/spring-docs/blob/master/pages/core/IoC-container.md#beans-classpath-scanning

注解类型:

@Controller:标记在控制层的类,注册为Bean组件

@Service:标记在业务逻辑层的类,注册为Bean组件

@Repository:标记在数据访问层的类,注册为Bean组件

@Component:标记在非上三层的普通类,注册为Bean组件

提示:接口不能使用注解

 

创建maven项目:

 

 

 

创建类和接口:

User类:

使用@Component注解:

package cn.cdulm.bean;

import org.springframework.stereotype.Component;

@Component
public class User {
}

 

配置spring的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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!--扫描包
    base-package:设置扫描的包
    -->
    <context:component-scan base-package="cn.cdulm"></context:component-scan>
</beans>

 

测试方法:

    @Test
    public void fun1(){
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring_ioc.xml");
        User user = ioc.getBean("user", User.class);
        System.out.println(user);
    }

 

运行结果:

 

 

 实现过程:

首先会去设置的包中扫描类,然后将类注入xml配置中,最后根据测试方法中的getBean()查找对应的Bean。

 

 

 

注解

四个注解中的非@Component注解都是按照@Component的规则进行细分:

以便达到一些目的,例如:

 

 

 

此时@Controller类型的Bean就不会被注入:

 

 

 

 

 

 

排除扫描:

 <context:exclude-filter type="" expression=""/>

这个属性在 context:component-scan 标签中,所以排除的是 context:component-scan 标签中存在的注解类:

例如:

<context:component-scan base-package="cn.cdulm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

意思是扫描 cn.cdulm 包中的类,然后排除掉 annotation 类型(注解类型)中 org.springframework.stereotype.Controller 注解类型的类。

 

type参数:

 

 

annotation:根据注解的完整限定名排除或包含

 assignable:根据类的完整限定名排除或包含

aspectj:org.example..*Service+ 根据切面表达式排除或包含(一般不使用)

regex:org\.example\.Default.*	根据正则表达式排除或包含

custom:org.example.MyTypeFilter	org.springframework.core.type .TypeFilter接口的自定义实现。(自定义,指定的类必须实现TypeFilter接口)(一般不使用)

 

 

 

包含扫描:

此时:

 

 

 设置为false并包含@Controller注解类:

 

 

 

 

 

 成功获取!

 

结论:

怎么使用注解将一个类注册为Bean的步骤:
    1.设置扫描包context: component-scan
    2.在对应的类名加上对应的注解
    

使用上面注解会自动将类名的首字母小写设置为Bean的名宁
  

 

posted on 2022-05-29 17:23  时间完全不够用啊  阅读(131)  评论(0编辑  收藏  举报