Spring-condition settings

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.