20191231 Spring official documents (Core 1.13-1.14)

1.13. Environment abstract

EnvironmentThe interface is integrated in the container abstract, can be modeled on two key aspects of the application environment: profileand properties.

profileIs only given profile is active registered with the naming container Bean defined only in logical groups. Bean can be assigned to the profile, either in XML or annotated defined. Environment-related objects profile role is to determine what the current profile (if any) is active, and the default profile case which (if any) should be active.

Property plays in almost all applications in an important role, and may be derived from a variety of sources: property files, JVM system properties, system environment variables, JNDI, Servlet context parameter, Properties Object, Map objects. Environment-related objects and attributes role is to provide users a convenient service interface for configuration properties and parses the source property.

1.13.1. Bean defined Profiles

Use @Profile

profile string can contain a simple profile name (e.g., production) or expression profile. expression profile allows more complex expression profile logic (e.g. production & us-east). It supports the following operators expression profile:

  • !: No logic
  • &: Logic and
  • |: Logical or

You can not mix & and without the use of parentheses | operator. For example, production & us-east | eu-centralit is not a valid expression. It must be expressed as production & (us-east | eu-central).

You can be @Profileused as a meta-annotation to create a custom combination comment. The following example defines a custom @Productionannotations, you can use it as @Profile("production")a substitute:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Profile("production")
public @interface Production {
}

If @Profilelabeled a @Configurationclass, unless one or more specified profile is active, otherwise it will ignore all associated with the class @Beanmethods and @Importcomments. If a @Componentor @Configurationcategory is marked with @Profile({"p1", "p2"}), unless activated profile "p1" or "p2", the class is not registered or otherwise processed. If a given profile to NOT operator ( !) is prefixed is not activated only when the registration profile annotated elements. For example, a given @Profile({"p1", "!p2"}), if the profile "p1" is active or profile "p2" is not active, it will be registered.

@Profile also be declared at the method level configuration to include only a specific class of Bean

@Bean method when using @Profile, special circumstances may arise: For heavy-duty @Bean method (similar to the overloaded constructor) Java method with the same name, @ Profile needs to be consistent across all declare overloaded methods conditions. If the conditions are not consistent, only overloaded methods in a condition statement is very important. Accordingly, @ Profile overloaded method can not be used to select specific parameters signature. When creating, parsing between the same bean factory method follow all the Spring constructors resolution algorithm.

To use a different profile define alternate bean conditions, please use a different Java method name, by using these names refer to the same attribute @Bean name bean name, as in the previous example. If the parameters are the same signature (e.g., all variants have no reference factory method), which is the first valid Java class represents the only way this arrangement (as only a specific method name and parameters of the signature).

XML Bean definitions Profile

XML is a corresponding entry <beans>element profileattributes.

XML does not support the corresponding term expression profile described above. However, by using the !cancel operator profile. You may apply a logic "and" nested profile as shown by the following example:

<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="production">
        <beans profile="us-east">
            <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
        </beans>
    </beans>
</beans>

In the previous example, if the production and us-east profile are active, the dataSource bean is disclosed.

Activating Profile

The most direct way is for configuring programmatically through ApplicationContext Environment API.

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("development");
ctx.register(SomeConfig.class, StandaloneDataConfig.class, JndiDataConfig.class);
ctx.refresh();

You can also spring.profiles.activeactivate declaratively profile attributes may be, the JVM system properties, or the servlet context parameters as an entry in the web.xml JNDI be specified by the system environment variable profile. In integration testing, you can use spring-testthe module @ActiveProfilesto declare the activity profile comments.

You can activate several profile. You can be programmed to setActiveProfiles()provide multiple profile name of the method
ctx.getEnvironment().setActiveProfiles("profile1", "profile2");

Declaratively, spring.profiles.activeyou can accept a comma-separated list of profile names
-Dspring.profiles.active="profile1,profile2"

Default Profile

The default profile is default.

You can pass Environmenton setDefaultProfiles()to change the default name of the profile, or through the use of spring.profiles.defaultproperty.

1.13.2. PropertySource abstract

Spring's Environment abstraction provides a configurable attribute hierarchy source search operation.

ApplicationContext ctx = new GenericApplicationContext();
Environment env = ctx.getEnvironment();
boolean containsMyProperty = env.containsProperty("my-property");
System.out.println("Does my environment contain the 'my-property' property? " + containsMyProperty);

In the preceding code snippet, we see a Spring asked whether the definition of an advanced method my-property attribute for the current environment. To answer this question, Environmentthe object in a group PropertySourceperforming a search on the subject. PropertySource is any key - the source of a simple abstract values, Spring of StandardEnvironment PropertySource arranged two objects, representing the attribute set JVM system ( System.getProperties()), a representative of the system environment variable set ( System.getenv()).

These default attributes in the presence of a source of StandardEnvironment, for use in separate applications. StandardServletEnvironment filled with default properties other sources (including servlet config and servlet context parameters). It can selectively enable JndiPropertySource.

Specifically, when you use StandardEnvironment, there is my-property system, property or my-property environment variable at run time, for the env.containsProperty("my-property")call will return true.

Search performed is hierarchical. By default, the system property takes precedence over the environment variable. So, if my-property during a call in two places at the same time set up a env.getProperty("my-property")property, the property value, the system will "win" and return. Please note that the property value will not merge, but will be completely covered by the previous entries.

For common StandardServletEnvironment, complete the following hierarchy, the highest priority entry at the top:

  • ServletConfigParameter (if applicable, for example, in the case of DispatcherServlet context)
  • ServletContextParameters (web.xml context parameter entry)
  • JNDI environment variable (java: comp / env / entry)
  • JVM system properties (-D command line parameters)
  • JVM system environment (operating system environment variables)

Most importantly, the whole mechanism is configurable. Maybe you want to integrate a custom attribute source to this search. To do this, realize and instantiate an instance of itself PropertySource PropertySources and add it to the collection in the current Environment. The following example shows how to do this:

ConfigurableApplicationContext ctx = new GenericApplicationContext();
MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
sources.addFirst(new MyPropertySource());

In the previous code, MyPropertySource has been added to the highest priority in the search. If it contains a my-property attribute, the attribute is detected and returns to support my-property attribute of the other PropertySource. MutablePropertySourcesAPI discloses a number of methods that allow for the source attribute sets precise operation.

1.13.3. Use @PropertySource

@PropertySource annotation mechanism provides added convenience and declared PropertySource into Spring Environment.
@PropertySource ( "classpath: /com/myco/app.properties")

@PropertySourceResource position in the presence of all the ${..}placeholders are based on a set of attributes of the source has been registered against the environment to resolve the
@PropertySource("classpath:/com/${my.placeholder:default/path}/app.properties")

Suppose my.placeholder source present in one of the registered attribute (e.g., attribute or system environment variables), then the placeholder resolves to the appropriate value. If not, then default/pathused as the default. If the default is not specified and can not be resolved attribute is thrown IllegalArgumentException.

@PropertySourceComments are repeatable, according to Java conventions 8. However, all such @PropertySource annotations need to declare at the same level, you can be configured in the class declaration directly, or you can customize annotations declared for the yuan in the same comment. Not recommended direct comments and metadata annotation mixed use, because direct comments will effectively cover yuan notes.

1.13.4. Statement parsing placeholder

Historically, the elements in a placeholder values ​​can only be resolved in accordance with JVM system properties or environment variables. This is no longer the case. Since Environment abstraction is integrated throughout the vessel, it is easy to route resolution placeholder through it. This means that you can configure the resolution process in any way you like. You can change the search system properties and environment variables priority, it can also completely remove them. You can also add your own if necessary to attribute the source to the mix.

Specifically, regardless of where the customer defined attributes, the following statements are valid as long as the properties available in the Environment:

<beans>
    <import resource="com/bank/service/${customer}-config.xml"/>
</beans>

1.14. Register a LoadTimeWeaver

When the LoadTimeWeavertime class is loaded into the Java Virtual Machine (JVM) in, Spring will be used to convert a dynamic class.

To enable load-time weaving, it can be @EnableLoadTimeWeavingadded to one of your @Configurationclass, as in the following example:

@Configuration
@EnableLoadTimeWeaving
public class AppConfig {
}

In addition, XML configuration, you can use context:load-time-weaverelements:

<beans>
    <context:load-time-weaver/>
</beans>

For Once ApplicationContextconfigured, the ApplicationContext any bean can be implemented LoadTimeWeaverAwareso as to receive the reference loading woven instance. When used in conjunction with Spring's JPA support, this feature is particularly useful because when weaving may need to be loaded during JPA class conversion.

Guess you like

Origin www.cnblogs.com/huangwenjie/p/12122631.html