github中的中文文档:
注解类型:
1 2 3 4 5 6 7 | @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就不会被注入:
排除扫描:
1 | <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参数:
1 2 3 4 5 6 7 8 9 | annotation:根据注解的完整限定名排除或包含 assignable:根据类的完整限定名排除或包含 aspectj:org.example..*Service+ 根据切面表达式排除或包含(一般不使用) regex:org\.example\.Default.* 根据正则表达式排除或包含 custom:org.example.MyTypeFilter org.springframework.core.type .TypeFilter接口的自定义实现。(自定义,指定的类必须实现TypeFilter接口)(一般不使用) |
包含扫描:
此时:
设置为false并包含@Controller注解类:
成功获取!
结论:
1 2 3 4 5 6 7 | 怎么使用注解将一个类注册为Bean的步骤: 1 .设置扫描包context: component-scan 2 .在对应的类名加上对应的注解 使用上面注解会自动将类名的首字母小写设置为Bean的名宁 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)