Spring IOC Related Configuration-summary

Source: Internet
Author: User
Tags aop class definition xml attribute

Based on XML configuration

Annotation-based configuration

Java-based class configuration

Based on Groovy DSL

Usage Scenarios

Beans come from third parties, such as DataSource, JdbcTemplate, and so on, because annotations cannot be annotated in a class, so it is better to configure them in XML mode.

Use a different namespace, such as Aop,context, only with XML-based configuration

Implementation-class user development for Beans

The logic of instantiating Bena is more complex

The overall logic of bean initialization can be controlled by code, and if the initialization logic is more complex, it is more appropriate for the Java class configuration

The advantage is that the process of bean initialization can be controlled flexibly through groovy scripting. If the logic of initializing beans is more complex, it is more appropriate to use a groovy DSL configuration

Bean definition

XML file through <bean> element definition Bean

<bean id= "..." Class= "..."/>

Add annotations in class

@Component

@Repository

@Service

@ Controller

Profile Scan package

<context:component-scan base-package= ""/>

Annotation Scan Package:

@ Componentscan use

@Configuration

Label class

@Bean standard provides beans, methods must provide the bean instantiation logic

 

Defines the bean in a groovy file through a DSL.

Userdao (Userdao)

Bean name

Specify by ID or name

<bean id= "Userdao" class=

"Com.jinwen.UserDao"/>

Default name

com.jinwen.userdao#0

@Component ("person

Default is the class first letter lowercase (not including the package name)

Other similar

@Bean ("person")

Name property.

Default name is method name

Defines the name of the bean through Groovy's DSL (type of bean, bean constructor parameter)

Logonservice

(Logonservice,

Userdao)

Bean injection

(Sett

ER injection, constructor injection)

Property Injection:

< Property> or through the P namespace

p:userdao-rf= "Userdao"

Ref property

Allow injection set

<map><list>< Array>

Constructor injection:

<constructor-arg ref= ""/>

<bean id= "class=" "autowire=" ByName "/>

@Autowired injected by type

@Autowired configuration using @qualifier injection by name

@ ...

 

@Bean (autowire = autowire.by_type)

Public Accountservice Accountservice () {

}

 

@Qualifier accept a string value that allows you to change the default qualified value (default bean name)

more flexible. The

method uses @autowired to bind the method into the parameter binding bean, and then enters the injection through code in the method. The

can also be injected by invoking the @bean method of the configuration class

is more flexible and can be injected at the method through the ref () method, such as ref ("Logdao")

Life process

Init-method and Destroy-method Properties

You can specify at most one initial method and one destruction method

@PostConstruct initialization

@PreDestroy Destruction

You can define multiple

<context:annotation-config/> activating annotations

The Initmethod or Destorymethod of the @Bean specifies an initialization or destruction method.

For initialization methods, the initialization logic can be flexibly defined directly within the method through code

by bean->

Bean.initmethod or Destorymethod specifies an initialization or destruction method

Bean Action Range

Scope property

<bean class= ":" Scope= "prototype"/>

@Scope setting the scope of action

@Scope ("prototype")

The Bean method defines the dimension @scope the specified range

by Bean->bean.scope

= "Prototype" specifies

Bean deferred Initialization

The default is defaulted by the <bean> Lazy-init property designation.

Inherit from <beans> default-lazy-init settings, default to False

Add @lazy specified through the class definition

such as @lazy (true)

Labeling @lazy annotations at the Bean method definition

by bean->

Bean.lazyinit=true Specify

Bean Dependency Relationship

Use the Depends-on property to separate multiple commas

Using @dependson annotations

This class is not created until the bean specified in the @dependson annotation has been created, or this class is not created.

When used at the method level, only has an impact on Java-based configuration

Using @dependson annotations

In general, XML configuration datasource,sessionfactory and other resource beans, in the XML with the Aop,context namespace for related topics configuration.

Beans developed in all other projects are configured in a way that is based on annotation configuration.

The spring container disables annotation assembly by default. The simplest way to open <context:annotation-config/>.

Spring container launches are broadly divided into two main stages

1, the container processes the configuration metadata and establishes the bean definitions that exist in the metadata, during which the bean definitions are validated, such as the <property> and <constructor-arg> elements providing the correct bean references, etc.

2, complete the creation of the bean, and then complete the dependency injection. In fact, not all Bena are created; During container startup, only the stateless scope bean is created. Bean creation triggers other dependent bean creation

There are three ways of automatic assembly: Bytype, ByName, constructor

@Value annotations

Spel expression:

@Value ("#{Jdbc.url}") Private String URL;

Placeholder mode

@Value ("${URL}") Private String URL;

${url} is a placeholder variable that is parsed by a special spring-based Bean, which is configured by <context:property-placeholder/>

<context:property-placeholder location= "Classpath:application.properties"/>

@PropertySource and @propertysources:

*.properties can be loaded from some places.

@Configutation

@PropertySource ("Classpath:1.properties")

@PropertySource ("Classpath:2.properties")

public class Xconfiguration () {

.......

}

Or

@PropertySources {

@PropertySource ("Classpath:1.properties")

@PropertySource ("Classpath:2.properties")

}

public class Xconfiguration () {

.......

}

@Import and @importresource

XML configuration: Configure multiple separate containers into one configuration by <importresource= "Xxx.xml"/>

@Configuration

@Import (Mockconfiguration.class)

public class xconfiguration{

。。。。

}

For Web Apps, Spring provides the Webapplicationcontextutils tool class that can return ApplicationContext instances of the web

Spring provides the Applicationcontextaware interface, which implements the Bean class for this interface, and the spring container injects itself into the bean instance during creation, and the bean can access its own container.

To alias a bean

<alias name = "alias=" "/>

Three ways to create a bean:

1. Construction method

2. Static or instance factory methods

3. Using spring's Factorybean interface to implement this interface, spring will find this bean class

The scope of the bean and its definition, "applicable @scope or Scope interface"

Singleton, prototype, Request (only for Webapplicationcontext), session.

The advantage of delaying lazy creation of a bean is that it accelerates the container startup time and consumes less memory.

Bean's life cycle

Three ways of Life callback, Init-method and. Properties, @PostConstruct annotations, Initializingbean, and Disposablebean interfaces, each declaring the Afterpropertiesset method and the Destroy method. If a bean implements the Initializingbean interface, the spring container will call the Afterpropertiesset method after the property injection is complete. If the Disposablebean interface is implemented, the bean is called before the Destroy method is destroyed

Different Environment configuration files

<import resource= "Classpath:/datasource-${targerplatform}.xml"/>

This placeholder can be parsed from environment variables in the operating system environment, or from JVM system properties such as setting the JVM table to Datagetplatform=dev.

Configuration file Properties

Spring.profiles.active=

spring.profiles.default=

The above is used to specify the activity and default profile values at run time

Beans profile properties, different configurations in different environments

<beans profile= "Dev,test" >

<bean ........./>

</beans>

<beans profile= "prod" >

<bean ........./>

</beans>

You can also use @profile to specify that only the specified profile is the active profile and the related bean is created

@Configuration

public class ch2config{

@Bean

@Profile ("Dev")

Public Foo Devfoo (@Value ("${name}") String name) {}

@Bean

@Profile ("prod")

Public Foo Devfoo (@Value ("${name}") String name) {}

}

Static Bean engineering, starting the property placeholder parsing mechanism (XML-based <context:property-placeholder/>)

@Bean

public static propertysourcesplaceholderconfigurerpropertysourcesplaceholderconfigurer () {

Return Propertysourcesplaceholderconfigurer ();

}

Environment: spring3.1 introduces environment to represent the environment in which the application is running. This interface allows you to manage the configuration file and property information used by your application.

Configurableenvironment environment = Application,getenvironment ();

Environment.setactiveprofiles ("Dev")

Add a new Mappropwetysource as the name placeholder to mutablepropertysources.

Mutablepropertysources propertysources =environment.getpropertysources ();

Propertysources.addlast (Newmappropwetysource ("MapSource"), Collections.singletonmap ("name", "my Foo");

Application.refresh ();

Beanfactory, Classpathxmlapplicationcontext, Annotationconfigapplicationcontext

Factory-bean, Factory-method: XML attribute used to create a bean using static and instance factory methods

Init-method and Destroy-method attributes: Specifies the XML attribute of the declaration period method in the bean definition

Envitonment, Configurationenvitonment: A spring interface used to abstract an application's working environment

Spring IOC Related Configuration-summary

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.