java配置也是spring4.0推薦的配置方式,完全可以取代xml的配置方式,也是springboot推薦的方式。
java配置是通過@configuation和@bean來實現的:
1、@configuation注解,說明此類是配置類,相當于spring的xml方式
2、@bean注解,注解在方法上,當前方法返回的是一個bean
eg:
此類沒有使用@service等注解方式
1
2
3
4
5
6
7
|
package com.wisely.heighlight_spring4.ch1.javaconfig; public class functionservice { public string sayhello(string world) { return "hello " + world + "!" ; } } |
此類沒有使用@service注解lei,也沒有使用@autowire注入bean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package com.wisely.heighlight_spring4.ch1.javaconfig; public class usefunctionservice { functionservice functionservice; public void setfunctionservice(functionservice functionservice) { this .functionservice = functionservice; } public string sayhello(string world) { return functionservice.sayhello(world); } } |
1、使用@configuation注解說明此類是一個配置類
2、使用@bean注解的方式注解在方法上,返回一個實體bean,bean的名稱是方法名。
3、注入functionservice的bean的時候,可以直接使用functionservice方法。
4、注解將functionservice作為參數直接傳入usefunctionservice。在spring容器中,只要在容器中存在一個bean,就可已在另一個bean的聲明方法的參數中直接使用。
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
|
package com.wisely.heighlight_spring4.ch1.javaconfig; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; @configuration public class javaconfig { @bean public functionservice functionservice() { return new functionservice(); } @bean public usefunctionservice usefunctionservice() { usefunctionservice usefunctionservice = new usefunctionservice(); usefunctionservice.setfunctionservice(functionservice()); return usefunctionservice; } @bean public usefunctionservice usefunctionservice(functionservice functionservice) { usefunctionservice usefunctionservice = new usefunctionservice(); usefunctionservice.setfunctionservice(functionservice); return usefunctionservice; } } |
測試類:
1
2
3
4
5
6
7
8
9
10
11
12
|
package com.wisely.heighlight_spring4.ch1.javaconfig; import org.springframework.context.annotation.annotationconfigapplicationcontext; public class main { public static void main(string[] args) { annotationconfigapplicationcontext context = new annotationconfigapplicationcontext(javaconfig. class ); usefunctionservice usefunctionservice = context.getbean(usefunctionservice. class ); system.out.println(usefunctionservice.sayhello( "java config" )); context.close(); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/JohnEricCheng/p/8621981.html