In--spring, the bean defines the use of profiles Javaconfig and XML configuration __profile

Source: Internet
Author: User

Original address: http://docs.spring.io/spring/docs/5.0.0.M4/spring-framework-reference/htmlsingle/#beans-property-source-abstraction
The bean definition profiles is a mechanism within the core container that registers different beans in different environments. The environment means to do different things for different users, this feature is useful in many scenarios, including the use of memory data sources during development, the use of monitoring components on QA or products using the same data source development period from Jndi, and the more efficient application of monitoring components when deployed Implementing a custom bean for the user's respective registration

Consider a scenario in a practical application that now requires a datasource. In the test environment, this configuration:

@Bean public
DataSource DataSource () {return
    new Embeddeddatabasebuilder ()
        . SetType ( Embeddeddatabasetype.hsql)
        . Addscript ("My-schema.sql").
        addscript ("My-test-data.sql")
        . Build ();

Now let's consider how to deploy this application to a QA or production environment, assuming that the application's data source will be registered to the Production Application server's Jndi directory. Our DataSource bean now looks like this:

@Bean (destroymethod= "") Public
DataSource DataSource () throws Exception {context
    CTX = new InitialContext (); C9/>return (DataSource) ctx.lookup ("Java:comp/env/jdbc/datasource");
}

The problem is how to switch between the two configurations in the current environment. Over time, spring users have designed a variety of ways to complete this switch, typically using the system environment variable and the xml<import/> bound,<import/> element to contain a ${placeholder} symbol, using an environment variable to set the ${ The value that the placeholder} symbol represents so that you can switch to the correct configuration file. The bean definition profiles is a core container feature that provides solutions for child problems.

To summarize the scenario above: the environment determines the bean definition, and finally discovers that we need to use some of the beans in some context, but not in other environments. You might say that you need to register a set of bean definitions in scene A and register another group in scenario B. Let's see how we can modify the configuration to complete this requirement.

@Profile

@Profile annotations are used to specify whether a component is eligible for registration when one or more profiles are activated. Using the example above, we can rewrite the datasource configuration as follows:

@Configuration
@Profile ("dev") public
class Standalonedataconfig {

    @Bean public
    DataSource DataSource () {return
        new Embeddeddatabasebuilder ()
            . SetType (Embeddeddatabasetype.hsql)
            . Addscript (" Classpath:com/bank/config/sql/schema.sql ")
            . Addscript (" Classpath:com/bank/config/sql/test-data.sql ")
            . Build ();
    }
}
@Configuration
@Profile ("production") public
class Jndidataconfig {

    @Bean (destroymethod= "")
    Public DataSource DataSource () throws Exception {context
        CTX = new InitialContext ();
        Return (DataSource) ctx.lookup ("Java:comp/env/jdbc/datasource");
    }

As mentioned earlier, using the @bean method, you will typically choose to use a JNDI lookup: Using the jnditemplate/jndilocatordelegatehelper of spring or the direct Jndiinitialcontext usage shown above, But not jndiobjectfactorybean this will make you declare that the return type must be of type Factorybean

@Profile can be used as a meta-annotation to create a custom combination annotation. The following example defines a custom @production annotation that is used to replace the

@Profile ("Production"):

@Target (Elementtype.type)
@Retention (retentionpolicy.runtime)
@Profile (" Production ") public
@interface production {
}

@Profile can also annotate methods that are used to configure a specified bean in a configuration class:

@Configuration public
class AppConfig {

    @Bean
    @Profile (' dev ') public
    DataSource Devdatasource () { return
        new Embeddeddatabasebuilder ()
            . SetType (Embeddeddatabasetype.hsql)
            . Addscript ("classpath:com/ Bank/config/sql/schema.sql ")
            . Addscript (" Classpath:com/bank/config/sql/test-data.sql ")
            . Build ();

    @Bean
    @Profile ("production") Public
    DataSource Productiondatasource () throws Exception {context
        CTX = New InitialContext ();
        Return (DataSource) ctx.lookup ("Java:comp/env/jdbc/datasource");
    }

If the @configuration class is marked with @profile, classes in @bean and @import annotations will be ignored unless the profile is activated. If a @component or @configuration class is marked as @profile ({"P1", "P2"}), then the profile ' P1 ' and/or ' P2 ' are activated. Otherwise, the class will not be registered/processed. If the given configuration file is in the NOT operator (. is prefixed, and if the profile is not active, the registered element will be registered. For example, a given @profile ({"P1", ". P2 "}), if the profile ' P1 ' activation or profile ' P2 ' is not activated, it is registered. XML Bean Definition Profiles

The XML configuration is a property of <beans>, and our example configuration above can be overridden with the following two XML files, as follows:

<beans profile= "Dev"
    xmlns= "Http://www.springframework.org/schema/beans"
    xmlns:xsi= "http://" Www.w3.org/2001/XMLSchema-instance "
    xmlns:jdbc=" Http://www.springframework.org/schema/jdbc "
    xsi: Schemalocation= "..." >

    <jdbc:embedded-database id= "DataSource" > <jdbc:script location=
        " Classpath:com/bank/config/sql/schema.sql "/>
        <jdbc:script location=" classpath:com/bank/config/sql/ Test-data.sql "/>
    </jdbc:embedded-database>
</beans>
<beans profile= "Production" xmlns= Http://www.springframework.org/schema/beans "xmlns:xsi=" http://
    Www.w3.org/2001/XMLSchema-instance "
    xmlns:jee=" Http://www.springframework.org/schema/jee "
    xsi: Schemalocation= "..." >

    <jee:jndi-lookup id= "DataSource" jndi-name= "Java:comp/env/jdbc/datasource"/>
</beans>

It is also possible to prevent the above two files from being separated by nesting <beans/> elements in the same file.

<beans xmlns= "Http://www.springframework.org/schema/beans"
    xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "
    xmlns:jdbc=" Http://www.springframework.org/schema/jdbc "
    xmlns:jee=" http:// Www.springframework.org/schema/jee "
    xsi:schemalocation=" >

    <!--other Bean definitions-->

    <beans profile= "Dev" >
        <jdbc:embedded-database id= "DataSource" >
            <jdbc:script location= "Classpath:com/bank/config/sql/schema.sql"/>
            <jdbc:script location= "classpath:com/bank/config/sql/ Test-data.sql "/>
        </jdbc:embedded-database>
    </beans>

    <beans profile=" Production " >
        <jee:jndi-lookup id= "DataSource" jndi-name= "Java:comp/env/jdbc/datasource"/>
    </beans>
</beans>
Activate profile

Now that we have updated the configuration, we still need to tell the spring which profile is active. If we start our example application now, we will see nosuchbeandefinitionexception thrown because the container cannot find a spring bean named DataSource.

Profile can be activated in a number of ways, but the most straightforward way is to rely on the environment API to configure it programmatically by ApplicationContext to obtain the environment:

Annotationconfigapplicationcontext CTX = new Annotationconfigapplicationcontext ();
Ctx.getenvironment (). Setactiveprofiles ("Dev");
Ctx.register (Someconfig.class, Standalonedataconfig.class, jndidataconfig.class);
Ctx.refresh ();

In addition, profiles may declare activation through the Spring.profiles.active property, which may be specified in the system environment variable, JVM System properties, Web.xml defined servlet context parameters. Or even a tuple (entry) that can be used as a jndi in integration testing. The profiles can be activated by @activeprofiles annotations in the Spring-test module.

Note that profiles is not a "or"-or "proposition, it is possible to activate multiple profiles at once, programmatically, simply by providing multiple profile names to the Setactiveprofiles () method, which accepts string ... Parameters:

Ctx.getenvironment (). Setactiveprofiles ("Profile1", "profile2");

Declaratively configured, spring.profiles.active can accept a comma-delimited list of profile names:

-dspring.profiles.active= "Profile1,profile2"
Default Profile

The default profile indicates that this profile is enabled by default. As follows:

@Configuration
@Profile ("default") public
class Defaultdataconfig {

    @Bean public
    DataSource DataSource () {return
        new Embeddeddatabasebuilder ()
            . SetType (Embeddeddatabasetype.hsql)
            . Addscript (" Classpath:com/bank/config/sql/schema.sql ")
            . Build ();
    }
}

If no profile is activated, the above datasource will be created, which can be viewed as a way to provide a default definition for one or more beans. If any of the beans are active, the default profile will not take effect.

The name of the default profile can be changed, using Setdefaultprofiles () in environment, or declaratively using the Spring.profiles.default property.

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.