本文介紹了利用注解配置Spring容器的方法,分享給大家,具體如下:
@Configuration標注在類上,相當于將該類作為spring的xml的標簽
1
2
3
4
5
6
|
@Configuration public class SpringConfiguration { public SpringConfiguration() { System.out.println( "初始化Spring容器" ); } } |
主函數進行測試
1
2
3
4
5
6
|
public class Main { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration. class ); } } |
利用注解AnnotationConfigApplicationContext加載ApplicationContext
運行結果如下
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2e5d6d97: startup date [Sat Dec 09 11:29:51 CST 2017]; root of context hierarchy
初始化Spring容器
利用@Bean向容器中添加bean實例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class User { private String username; private int age; public User(String username, int age) { this .username = username; this .age = age; } public void init(){ System.out.println( "初始化User..." ); } public void say() { System.out.println(String.format( "Hello,my name is %s,I am %d years old " , username, age)); } public void destory(){ System.out.println( "銷毀User ..." ); } } |
1
2
3
4
5
6
7
8
9
10
11
12
|
@Configuration public class SpringConfiguration { public SpringConfiguration() { System.out.println( "初始化Spring容器" ); } //@Bean注解注冊bean,同時制定初始化和銷毀的方法 @Bean (name = "user" , initMethod = "init" , destroyMethod = "destory" ) @Scope ( "prototype" ) public User getUser() { return new User( "tom" , 20 ); } } |
@Bean注解在返回實例的方法上,如果沒有指定bean的名字,則默認與標注的方法名稱相同
@Bean注解默認作用域為單例的Singleton作用域
利用@ComponentScan添加自動掃描@Service,@Ripository,@Controller,@Component注解
1
2
3
4
5
6
7
8
|
@Component public class Cat { public Cat() { } public void say() { System.out.println( "I am a cat" ); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Configuration @ComponentScan (basePackages = "com.spring.annotation.ioc" ) public class SpringConfiguration { public SpringConfiguration() { System.out.println( "初始化Spring容器" ); } //@Bean注解注冊bean,同時制定初始化和銷毀的方法 @Bean (name = "user" , initMethod = "init" , destroyMethod = "destory" ) @Scope ( "prototype" ) public User getUser() { return new User( "tom" , 20 ); } } |
利用basePackages掃描包配置路徑
運行結果如下
1
2
3
4
|
初始化Spring容器 初始化User... Hello,my name is tom,I am 20 years old I am a cat |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/JavaMoo/article/details/78758239