spring-注解
spring框架提供xml文件的配置,也提供基于注解的方式實現配置任何的Bean實例,目前,struts2、hibernate和spring都相繼支持基于注解的實現方式。spring要求程序員指定搜索哪些路徑下的java類,spring會把合適的java類全部注冊成spring bean。
下面對基本的注解進行簡要的解釋和使用示例。
1、@Component:標注一個普通的spring bean
(1)、編寫java代碼
student:
package cn.study.basic.test7;import org.springframework.stereotype.Component;@Component
public class Student implements People {@Overridepublic void action() {System.out.println("studing^^");}}
worker:
package cn.study.basic.test7;import org.springframework.stereotype.Component;@Component
public class Worker implements People {@Overridepublic void action() {System.out.println("working");}} (2)、bean.xml配置文件,base-package指定要搜索的包的路徑
<context:component-scan base-package="cn.study.basic.test7.Student"></context:component-scan> 補充:context:component節(jié)點下有include-filter和exclude-filter節(jié)點,配置文件的格式如下
<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類滿足這種規(guī)則,即使這些java類沒有使用annotation標注,spring一樣將會把它們當做Bean類來處理
- type:指定過濾器類型
- expression:指定過濾器所需要的表達式
? ? ? ?spring支持4種過濾器:
- ?regex:正則表達式過濾器,配置改正則表達式的java類,如:.*Chinese
- annotation: annotation過濾器
- aspectj:AspectJ過濾器
- assignable:類名過濾器該過濾器直接指定一個java類
(3)、代碼測試
package cn.study.basic.test7;import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestMain {@Testpublic 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,標注一個業(yè)務邏輯組件類,通常是多層架構的Service層
(3)@Controller 標注一個控制器組件類,在struts中通常是Action層
(4)@Repository 標注一個DAO組件類
(5)@Scope():指定當前的Bean示例的作用域,默認值是singleton
(6)@Resource:
(7)@PostConstruct:作用與在配置文件中的init-method一樣
(8)@PreDestroy:作用與在配置文件中的destroy-method一樣
?
轉載于:https://www.cnblogs.com/gyouxu/p/4008411.html
總結
- 上一篇: 《相和歌辞·王昭君二首》第二句是什么
- 下一篇: 将ADS1.2的工程迁移到KEIL上-基