Spring Conditions comment @Conditional

  Spring4 provides a more general way to create conditions for Bean, and that the use of @Conditional comment.

  Example:

  IfCreate by modifying values ​​in the configuration file to control the creation of a Bean.

  (1) create a class that implements the Condition interface methods to achieve matches, matches the results returned by the method determines whether Bean is created.

  

 
 
package learnspring.learnspring.conditional;

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

/**
* @author 肖政宇
* @date 2019-09-26 14:33
* 说明:判断条件
*/
public class MyCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
String ifCreate = conditionContext.getEnvironment() .getProperty ( "ifCreate" ) ;
IF ( "to true" .equals (ifCreate )) {
. the System Out.println ( "profile, ifCreate value to true" ) ;
return to true; } the else { . the System OUT .println ( "profile, ifCreate value to false" ) ; return to false; } } }






 

(2)Bean

 
 
learnspring.learnspring.conditional Package Penalty for ; 

/ **
* @author Xiao Zhengyu
* @date 2019-09-26 14:45
* Description:
* /
public class the DemoBean { public the DemoBean () { System. out.println ( "the Hello, already the DemoBean created "! ) ; } }




 

(3) java class configuration

 
 
package learnspring.learnspring.conditional;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

/**
* @author 肖政宇
* @date 2019-09-26 14:46
* 说明:
*/
@Configuration
public class MyConditionalConfiguration {

@Bean
@Conditional(MyCondition.class)
public DemoBean createBeanConditional() {
return new DemoBean();
}
}
 

(4) configuration file

 

(5) operating results

 

Guess you like

Origin www.cnblogs.com/KenBaiCaiDeMiao/p/11591929.html