Skip to content

Commit 5cfcb5d

Browse files
author
曾梓健
committed
@import理解:优先导入@import的配置类
1 parent 4462865 commit 5cfcb5d

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.hand.test;
2+
3+
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
4+
import org.springframework.context.ApplicationContext;
5+
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
6+
import org.springframework.context.annotation.Bean;
7+
import org.springframework.context.annotation.Configuration;
8+
import org.springframework.context.annotation.Import;
9+
10+
/**
11+
* @author zijian.zeng@hand-china.com
12+
* @since 2023-01-31
13+
*/
14+
@Configuration
15+
// 通常是引入配置类
16+
@Import(ConfigB.class)
17+
public class ConfigA {
18+
19+
@Bean
20+
@ConditionalOnMissingBean
21+
public ServiceInterface getServiceA() {
22+
return new ServiceA();
23+
}
24+
25+
public static void main(String[] args) {
26+
// AnnotationConfigApplicationContext 参数指定 Java文件的[配置]类
27+
ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigA.class);
28+
ServiceInterface bean = ctx.getBean(ServiceInterface.class);
29+
bean.test();
30+
}
31+
}
32+
33+
@Configuration
34+
class ConfigB {
35+
36+
@Bean
37+
@ConditionalOnMissingBean
38+
public ServiceInterface getServiceB() {
39+
return new ServiceB();
40+
}
41+
}
42+
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.hand.test;
2+
3+
/**
4+
* @author zijian.zeng@hand-china.com
5+
* @since 2023-01-31
6+
*/
7+
public interface ServiceInterface {
8+
9+
void test();
10+
}
11+
12+
class ServiceA implements ServiceInterface {
13+
@Override
14+
public void test() {
15+
System.out.println("ServiceA");
16+
}
17+
}
18+
19+
class ServiceB implements ServiceInterface {
20+
@Override
21+
public void test() {
22+
System.out.println("ServiceB");
23+
}
24+
}

0 commit comments

Comments
 (0)