In order to produce a more suitable bean under different conditions, you can configure its condition using condition. If there is a bean,id for Magicbean, it is generated only if it has a magic attribute, as follows:
Javaconfig mode: Just add @conditional where you want to declare the bean
1 PackageCom.myapp;2 3 ImportOrg.springframework.context.annotation.Bean;4 Importorg.springframework.context.annotation.Conditional;5 6 Public classMagicbean {7@Bean//explicitly declares a bean,id default to the method name8@Conditional (magicexistsconditional.class)//generates the bean's condition judgment, the parameter type is class, accepts the return Boolean value, is true to generate the bean otherwise does not generate9 PublicMagicbean Magicbean () {Ten return NewMagicbean (); One } A}
How is the parameter (magicexistsconditional.class) written?
1 PackageCom.myapp;2 3 Importorg.springframework.context.annotation.Condition;4 ImportOrg.springframework.context.annotation.ConditionContext;5 Importorg.springframework.core.env.Environment;6 ImportOrg.springframework.core.type.AnnotatedTypeMetadata;7 8 Public classMagicexistsconditionalImplementscondition{9 Ten @Override One Public Booleanmatches (Conditioncontext arg0, Annotatedtypemetadata arg1) { A //TODO auto-generated Method Stub -Environment Env=arg0.getenvironment ();//Get Context Environment - returnEnv.containsproperty ("Magic");//Check if the Magic attribute is included the } - -}
This is done only by Conditioncontext type of arg0 to get the environment type of env, through the env call method to determine whether there is a magic attribute.
and Conditioncontext and Annotatedtypemetadata are interfaces, which define a number of methods, see "Spring Combat (4th edition)" p75-p78.
Spring-condition settings