Learn more about Spring (dependency injection). spring Injection

Source: Internet
Author: User

Learn more about Spring (dependency injection). spring Injection
I. Overview

The Spring framework is created to simplify the development of Java EE applications. Spring can implement many functions, but the underlying layers of these functions depend on its two core features, namely dependency injection and cross-section programming. Almost everything Spring does can be traced back to one or more of the following policies:

POJO-based lightweight and minimal invasive programming;
Loose coupling is achieved through dependency injection and interface-oriented;
Declarative Programming Based on aspect and Convention;
Reduce the sample code by cropping and templates.

Spring has three basic visions:

Use DI for low coupling
Use the AOP aspect to achieve high cohesion
Use a template to remove sample code, such as jdbcTemplate.

Ii. Bean

Containers are the core of the Spring framework. The Spring container uses DI to manage the components (beans) that constitute the application. It creates associations between the components that collaborate with each other. Undoubtedly, these objects are simpler and cleaner, easier to understand and reuse, and easier to unit test.

Spring defines Multiple scopes for each Bean, and is created in the singleton mode by default:

Singleton: Only one bean instance is created throughout the application.
Prototype: A new bean instance is created every time a Prototype is injected or obtained through the Spring application context.
Session: Creates a bean instance for each Session in a Web application.
Request (Rquest): Creates a bean instance for each request in a Web application.

Bean lifecycle:

Spring comes with various types of context (suitable for loading the required Bean using Spring context in common classes ):

AnnotationConfigApplicationContext: loads Spring application context from one or more Java configuration classes

ApplicationContext applicationContext = new AnnotationConfigApplicationContext (JavaConfig. class );View Code

AnnotationConfigWebApplicationContext: loads the Spring Web application context from one or more Java-based configuration classes.
ClassPathXmlApplicationContext: loads the context definition from one or more XML configuration files in the class path, and uses the definition file of the application context as a class resource.

ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("applicationContext. xml ");View Code

FileSystemXmlapplicationcontext: loads context definitions from one or more XML configuration files in the file system.
XmlWebApplicationContext: loads context definitions from one or more XML configuration files under a Web application.

Iii. Dependency Injection

1. @ ComponentIndicates that this class will act as a component class and notify Spring to create a bean for this class (the bean ID is named in lowercase at the first letter of the class name by default ). However, component scanning is disabled by default. We also need to display and configure Spring, and then run it to search for @ Component (similar@ Repository @ Service @ Controller) Annotation class, and create a bean for it. There are three ways to configure Spring to create Bena:

* Automatic Assembly: 1. Create a configuration class.@ ConfigurationIndicates that this class is added to a configuration class@ ComponentScan(BasePackages = {"package name 1", "package name 2"} Or basePackageClasses = {a Class of Package 1, a Class of package 2 }) it scans the same package as the configuration class and all the sub-packages under this package.

2. Spring XML configuration method: <context: component-scan base-package = ""/>

* Display configuration in JavaConfig (applicable to third-party class library components assembled into your own applications)

@ Configurationpublic class JavaConfig {@ Bean (name = "base64Util") public Base64Util getBase64Util () {return new Base64Util ();} @ Bean (name = "base64UtilExpand ") // The default Bean name for this display configuration is the method name. Therefore, it is best to display and configure public Base64UtilExpand getBase64UtilExpand () {// For this created bean, You need to reference other beans. Spring handles this as follows: when the referenced bean is not created, Spring intercepts this reference and waits until the referenced bean is created. The Singleton mode of Spring bean is guaranteed. return new Base64UtilExpand (getBase64Util ();} @ Bean (name = "base64UtilExpand") public Base64UtilExpand encode (Base64Util base64Util) {return new Base64UtilExpand (base64Util );}}View Code

* Display configuration in XML. The oldest method is rarely used. There are two ways to inject, constructor injection and set injection:

<! -- Constructor injection --> <bean id = "cDPlayer" class = "com. CDPlayer "> <constructor-arg ref =" compactDisc "> </bean> <bean id =" cDPlayer "class =" com. CDPlayer "> <constructor-arg value =" compactDisc "> </bean> <bean id =" cDPlayer "class =" com. CDPlayer "> <constructor-arg> <list> <value> </list> </constructor-arg> </bean> <! -- Setter injection --> <bean id = "cDPlayer" class = "com. CDPlayer "> <property name =" compactDisc "ref =" compactDisc "> </bean> <bean id =" cDPlayer "class =" com. CDPlayer "> <property name =" compactDisc "value =" compactDisc "> <! -- Assembly literal: --> </bean> Assembly set <bean id = "cDPlayer" class = "com. CDPlayer "> <property name =" compactDisc "value =" compactDisc "> <property name =" "> <list> <value> </value> <! -- Assembly set --> </list> </property> </bean>View Code

2. @ scopeSpecify the scope of bean creation. Spring creates the bean in singleton mode by default. However, there are also special cases. It should be noted that if a class is injected with the Bean of the Session and Request scope, this Bean is generated during user requests, it does not exist when Spring is running. Here Spring is handled as follows: it is injected to a proxy of the corresponding Bean. When a user request generates a session or request-scope Bean, the proxy is connected to the corresponding Bean to process the request...

 

Prototype: @ Scope (ConfigurableBeanFactory. SCOPE_PROTOTYPE)

Session :( Interface) @ Scope (value = WebApplicationContext. SCOPE_SESSION, proxyMode = ScopedProxyMode. INTERFACES)

(Specific Class) @ Scope (value = WebApplicationContext. SCOPE_SESSION, proxyMode = ScopedProxyMode. TARGET_CLASS)

Of course, you can also configure it in XML:

<Bean id = "shoppingCart2" class = "com. entity. shoppingCart2 "scope =" session "> <aop: scoped-proxy-target-class =" false "/> </bean>View Code

3. Qualifier(Use less)

 @ ProfileDetermines which beans can be activated. Note that beans without a specified profile will always be created and have no relationship with which profile to activate.

@ ConditionalGiven a Class, this Class implements the matches method of the Codition interface. If this method returns true, the bean is generated; otherwise, the bean is not generated.

 @ PrimaryA common situation is that an interface has only one implementation class, so after @ Autowire is used, Spring can go to the corresponding implementation class. What if an interface has multiple implementation classes? @ Component and @ primary are both used to indicate which implementation class is used first.

@ Qualifier@ Primary cannot guarantee which bean is selected because @ primary can be used on multiple implementation classes. Therefore, you can use @ Qualifter ("bean") to specify the bean name in the implementation class. The @ Autowire Injection Interface uses Qualifier to specify the bean name of the implementation class. You can also use @ Resource (name = "") to specify the class name.

4. Read the properties File

(1) @ PropertySourceReferences the properties file in the class path and obtains the variable value of properties using the Environment class. Example: @ PropertySource ("classpath: mongo. properties ")

@ Configuration @ PropertySource ("classpath: mongo. properties ") public class JavaConfig {@ Bean (name =" mongoUtil ") public classes util getMongoUtil (Environment env) {return new classes util (env. getProperty ("mongo. host "), env. getProperty ("mongo. port "), env. getProperty ("mongo. database "), env. getProperty ("mongo. username "), env. getProperty ("mongo. password "));}}View Code

(2) placeholders

Placeholders in Spring are in the form of $. In the code file, we can use@ ValueAnnotation injects the value of the configuration file into the variable. To use placeholders, We must configure a PropertySourcesPlaceholderConfigurer class to generate related beans, or let Spring automatically generate for us through XML configuration:

@ Configuration @ PropertySource ("classpath: mongo. properties") public class JavaConfig {@ Bean (name = "propertySourcesPlaceholderConfigurer") public writable handler () {return new PropertySourcesPlaceholderConfigurer ();}}View Code

Or:

<! -- The Spring placeholder $ {}--> <context: property-placeholder location = "classpath: mongo. properties" file-encoding = "UTF-8"/> can be used to read the configuration file.View Code

The usage is as follows:

@ RunWith (SpringJUnit4ClassRunner. class) // @ ContextConfiguration (classes = JavaConfig. class) @ ContextConfiguration (locations = "classpath: applicationContext. xml ") public class Test06 {@ Value (" $ {mongo. host} ") private String host; @ Test public void test06 () {System. out. println (host );}}View Code 4. Expression Language

Spring Expression Language (SpEL) is a flexible Expression Language with many features, including:

Use the bean ID to reference the bean;
Call methods and access object attributes;
Perform arithmetic, relational, and logical operations on values;
Regular Expression matching;
Set Operations.

SpEL adopts the form:

1. Representing the literal value: #{3.14 }#{ 'hello' }#{ false}
2. Reference beans, attributes, and methods # {bean }#{ bean. artist }#{ bean. toUpperCase () }#{ bean ?. ToUpperCase ()} (it indicates that if bean is null, null is returned and no method is called)
3. Reference a class # {T {java. lang. Math}. PI}
4. Ternary expression # {bean. score> 1000? "Win": "los"} empty # {bean. score? : "Win "}
5. Regular Expression # {bean. email matches 'expression '}
6. Calculate the set # {bean. song [4]. title}
Query operator (.?) # {Bean. songs .? [Artist eq 'hello']}
Match the first (. ^) # {bean. songs. ^ [artist eq 'hello']}
Match the last (. $ ):

# {Bean. songs. $ [artist eq 'hello']}

Projection Operator (.!) # {Bean. songs .! [Title]}

<Bean id = "carl" class = "com. springinaction. springidol. instrumentalist "> <property name =" song "value =" # {kenny. song} "/> </bean>View Codepublic static class FieldValueTestBean {@ Value ("# {systemProperties ['user. region ']} ") private String defaultLocale; public void setdefalocallocale (String defaultLocale) {this. defaultLocale = defaultLocale;} public String getdefalocallocale () {return this. defaultLocale ;}}View Code

Spring creates two special options for SpEL: systemEnvironment and systemProperties.
SystemEnvironment contains all environment variables on the machine where the application is located.
SystemProperties contains all the attributes set when the java application starts.

V. JUnit Testing
@ RunWith (SpringJUnit4ClassRunner. class) // @ ContextConfiguration (classes = JavaConfig. class) load the configuration class @ ContextConfiguration (locations = "classpath: applicationContext. xml ") // load the configuration file public class Test02 {@ Resource (name =" iceCream ") private Dessert dessert; @ Test public void test02 () {dessert. sys ();}}

 

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.