0%

基于编程方式实现条件装配

本文主要讲通过编程方式来实现条件装配 —— @Condition


首先我们添加判断类

OnSystemPropertyCondition.java

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
package xyz.suiwo.diveinspringboot.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
* @author suiwo
* @title: OnSystemPropertyCondition
* @date 2019-06-06 15:04
*
* 系统属性条件判断
*/
public class OnSystemPropertyCondition implements Condition {

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata.getAnnotationAttributes(ConditionalOnSystemProperty.class.getName());
String propertyName = String.valueOf(attributes.get("name"));
String propertyValue = String.valueOf(attributes.get("value"));
String javaPropertyValue = System.getProperty(propertyName);
System.out.println(javaPropertyValue);

return propertyValue.equals(javaPropertyValue);
}
}

然后添加注解类

ConditionalOnSystemProperty.java

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
package xyz.suiwo.diveinspringboot.condition;

import org.springframework.context.annotation.Conditional;

import java.lang.annotation.*;

/**
* @author suiwo
* @title: ConditionalOnSystemProperty
* @date 2019-06-06 15:02
*
* Java系统属性条件判断
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnSystemPropertyCondition.class)
public @interface ConditionalOnSystemProperty {

/**
* Java系统属性名称
* @return
*/
String name();

/**
* Java系统属性值
* @return
*/
String value();

}

最后我们添加引导启动类

ConditionalSystemPropertyBootstrap.java

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
package xyz.suiwo.diveinspringboot.bootstrap;

import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import xyz.suiwo.diveinspringboot.condition.ConditionalOnSystemProperty;

/**
* @author suiwo
* @title: ConditionalSystemPropertyBootstrap
* @date 2019-06-06 15:10
*
* 系统属性条件引导类
*/
public class ConditionalSystemPropertyBootstrap {

@Bean
@ConditionalOnSystemProperty(name = "user.name",value = "zhangsan")
public String helloWorld(){
return "Hello world zhangsan";
}

@Bean
@ConditionalOnSystemProperty(name = "user.name",value = "suiwo")
public String helloW(){
return "Hello world suiwo";
}

public static void main(String[] args) {
ConfigurableApplicationContext context =
new SpringApplicationBuilder(ConditionalSystemPropertyBootstrap.class)
.web(WebApplicationType.NONE)
.run(args);
System.out.println(context.getBean("helloW",String.class));
System.out.println(context.getBean("helloWorld",String.class));

//关闭上下文
context.close();
}
}

当我们运行后会发现终端运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.5.RELEASE)

2019-06-14 11:28:50.783 INFO 30704 --- [ main] s.d.b.ConditionalSystemPropertyBootstrap : Starting ConditionalSystemPropertyBootstrap on suiwoMBP with PID 30704 (/Users/dive-in-spring-boot/target/classes started by suiwo in /Users/dive-in-spring-boot)
2019-06-14 11:28:50.790 INFO 30704 --- [ main] s.d.b.ConditionalSystemPropertyBootstrap : No active profile set, falling back to default profiles: default
suiwo
suiwo
2019-06-14 11:28:51.251 INFO 30704 --- [ main] s.d.b.ConditionalSystemPropertyBootstrap : Started ConditionalSystemPropertyBootstrap in 1.218 seconds (JVM running for 1.945)
Hello world suiwo
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'helloWorld' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:769)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1111)
at xyz.suiwo.diveinspringboot.bootstrap.ConditionalSystemPropertyBootstrap.main(ConditionalSystemPropertyBootstrap.java:36)

Process finished with exit code 1

由此可见当不满足条件时,此时bean无法装配