日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

spring-注解

發布時間:2023/11/27 生活经验 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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節點下有include-filterexclude-filter節點,配置文件的格式如下

<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)、代碼測試

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,標注一個業務邏輯組件類,通常是多層架構的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

總結

以上是生活随笔為你收集整理的spring-注解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。