spring-ioc的使用
ioc容器在很多框架里都在使用,而在spring里它被應用的最大廣泛,在框架層面上,很多功能都使用了ioc技術,下面我們看一下ioc的使用方法。
- 把服務注冊到ioc容器
- 使用屬性注入反射對應類型的實例
- 多態情況下,使用名稱反射類型的實例
把服務注冊到ioc容器
@bean注冊組件
使用@bean注解進行類型的注冊,默認你的ioc容器里類型為bean的返回值,名稱為bean所有的方法名,與你的包名稱沒有直接關系,如果你的接口有多種實現,在注冊時可以使用@bean("lind")這種方式來聲明。
@component,@configuration,service,repository注冊組件
這幾個注解都是在類上面聲明的,而@bean是聲明在方法上的,這一點要注意,這幾個注解一般是指對一個接口的實現,在實現類上加這些注解,例如,一個數據倉儲接口userrepository,它可以有多種數據持久化的方式,如sqluserrepositoryimpl和mongouserrepositoryimpl,那么在注冊時你需要為他們起一個別名,如@repository("sql-userrepositoryimpl) qluserrepositoryimpl,默認的名稱是類名,但注意類名首字母為小寫
。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
public interface emaillogservice { void send(string email, string message); } @component () public class emaillogservicehttpimpl implements emaillogservice { private static final logger logger = loggerfactory.getlogger(emaillogservicehttpimpl. class ); @override public void send(string email, string message) { assert .notnull(email, "email must not be null!" ); logger.info( "send email:{},message:{}" , email, message); } } @component ( "email-socket" ) public class emaillogservicesocketimpl implements emaillogservice { private static final logger logger = loggerfactory.getlogger(emaillogservicesocketimpl. class ); @override public void send(string email, string message) { assert .notnull(email, "email must not be null!" ); logger.info( "send email2:{},message:{}" , email, message); } } // 看一下調用時的測試代碼 @resource (name = "email-socket" ) emaillogservice socketemail; @autowired @qualifier ( "emaillogservicehttpimpl" ) emaillogservice httpemail; @test public void testioc2() { socketemail.send( "ok" , "ok" ); } @test public void testioc1() { httpemail.send( "ok" , "ok" ); } |
在程序中使用bean對象
1.使用resource裝配bean對象
在通過別名
調用bean時,你可以使用@resource注解來裝配對象
2.使用@autowired裝配bean對象
也可以使用 @autowired
@qualifier( "emaillogservicehttpimpl")兩個注解去實現程序中的多態
。
使用場景
在我們有些相同行為而實現方式不同的場景中,如版本1接口與版本2接口,在get方法實現有所不同,而這
兩個版本都要同時保留,這時我們需要遵守開閉原則,擴展一個新的接口,而在業務上對代碼進行重構,
提取兩個版本相同的方法到基類,自己維護各自獨有的方法,在為它們的bean起個名字,在裝配時,通過
bean的名稱進行裝配即可。
寫個偽代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
class api_version1(){ @autowired @qualifier ( "print-version1" ) printservice printservice; } class api_version2(){ @autowired @qualifier ( "print-version2" ) printservice printservice; } class baseprintservice{} interface printservice{} @service ( "print-version1" ) class printserviceimplversion1 extends baseprintservice implements printservice{} @service ( "print-version2" ) class printserviceimplversion2 extends baseprintservice implements printservice{} |
以上所述是小編給大家介紹的java的spring-ioc的使用詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/lori/p/10512402.html