spring-注解
spring框架提供xml文件的配置,也提供基于注解的方式实现配置任何的Bean实例,目前,struts2、hibernate和spring都相继支持基于注解的实现方式。spring要求程序员指定搜索哪些路径下的java类,spring会把合适的java类全部注册成spring bean。
下面对基本的注解进行简要的解释和使用示例。
1、@Component:标注一个普通的spring bean
(1)、编写java代码
student:
1 2 3 4 5 6 7 8 9 10 11 12 13 | package cn.study.basic.test7; import org.springframework.stereotype.Component; @Component public class Student implements People { @Override public void action() { System.out.println( "studing^^" ); } } |
worker:
1 2 3 4 5 6 7 8 9 10 11 12 13 | package cn.study.basic.test7; import org.springframework.stereotype.Component; @Component public class Worker implements People { @Override public void action() { System.out.println( "working" ); } } |
(2)、bean.xml配置文件,base-package指定要搜索的包的路径
1 | <context:component-scan base- package = "cn.study.basic.test7.Student" ></context:component-scan> |
补充:context:component节点下有include-filter和exclude-filter节点,配置文件的格式如下
1 2 3 4 | <context:component-scan base- package = "cn.study.basic.test7" > <context:include-filter type= "regex" expression= "" /> <context:exclude-filter/> </context:component-scan> |
- include-filter用于指定spring bean类,只要位于指定路径下的java类满足这种规则,即使这些java类没有使用annotation标注,spring一样将会把它们当做Bean类来处理
- type:指定过滤器类型
- expression:指定过滤器所需要的表达式
spring支持4种过滤器:
- regex:正则表达式过滤器,配置改正则表达式的java类,如:.*Chinese
- annotation: annotation过滤器
- aspectj:AspectJ过滤器
- assignable:类名过滤器该过滤器直接指定一个java类
(3)、代码测试
1 2 3 4 5 6 7 8 9 10 11 12 13 | package cn.study.basic.test7; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestMain { @Test public void testMain() throws Exception { ApplicationContext ctx= new ClassPathXmlApplicationContext( "bean.xml" ); System.out.println(java.util.Arrays.toString(ctx.getBeanDefinitionNames())); } } |
运行代码,结果如下:
[student, worker, org.springframework.context.annotation.internalConfigurationAnnotationProcessor, org.springframework.context.annotation.internalAutowiredAnnotationProcessor, org.springframework.context.annotation.internalRequiredAnnotationProcessor, org.springframework.context.annotation.internalCommonAnnotationProcessor, dog, dd, myBeanPostProcessor, ch, axe, account, cn.study.basic.EmailListener#0, pl, spContext]
从上面的结果可以看出,如果没有在component中进行命名,则spring框架默认使用类的名称,并且小写首字母
(2)@Service,标注一个业务逻辑组件类,通常是多层架构的Service层
(3)@Controller 标注一个控制器组件类,在struts中通常是Action层
(4)@Repository 标注一个DAO组件类
(5)@Scope():指定当前的Bean示例的作用域,默认值是singleton
(6)@Resource:
(7)@PostConstruct:作用与在配置文件中的init-method一样
(8)@PreDestroy:作用与在配置文件中的destroy-method一样
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步