Spring Journey of Use (i)----bean assembly

Source: Internet
Author: User

Basic Configuration
    • Enable Component Scan Configuration
                    java class profile mode package  Com.springapp.mvc.application; import org.springframework.context.annotation.componentscan;import  org.springframework.context.annotation.configuration; /** * created by xuc  on 2018/1/7. *  Configuration Class  */@ComponentScan (basepackages = {"COM.SPRINGAPP.MVC"}) @ configurationpublic class application {}  Note: Here @configuration for declaring the class as a profile class, @ Componentscan to enable scanning for claims, if the underlying package properties are not configured, the current package is scanned by default, otherwise the package XML file for the scan base package definition is configured <beans xmlns= "/HTTP Www.springframework.org/schema/beans "       xmlns:xsi=" http://www.w3.org/2001/ Xmlschema-instance "       xmlns:context=" Http://www.springframework.org/schema/context "       xsi:schemalocation= "http://www.springframework.org/schema/beans        HTTP ://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context http://www.springframework.org/ Schema/context/spring-context.xsd ">    <context:component-scan base-package=" Com.springapp.mvc "/>    <bean class=" Org.springframework.web.servlet.view.InternalResourceViewResolver ">        <property  name= "prefix"  value= "/web-inf/pages/"/>        <property name= "suffix"  value= ". jsp"/>    </bean></beans>
    •   Manual assembly of Beans
          In most cases we use component scans to load beans, but sometimes when using a third-party framework, some configuration classes need to be specified, in which case the manual configuration is more appropriate                     Java class assembly mode package com.springapp.mvc.application;  import com.springapp.mvc.easyBean.Braves;import com.springapp.mvc.easyBean.Sword;import  org.springframework.context.annotation.bean;import org.springframework.context.annotation.componentscan; import org.springframework.context.annotation.configuration; /** * created by  xuc on 2018/1/7. *  Configuration Class  */@ComponentScan (basepackages = {"Com.springapp.mvc" }) @Configurationpublic  class Application {    @Bean (name =  "Braves")     Public braves braves ()  {        return new braves (Sword ());    }    @Bean     public braves braves1 ()  {        BRaves braves = new braves ();        Braves.setsword (Sword ());        return braves;   }    @Bean     Public sword sword ()  {         Return new sword ();   }}              Note : The configuration file class is declared here first, and then by @bean annotations on the method, spring will know that the method will return a bean and register it in the spring context. @Bean Note If you configure the Name property, the Bean's ID is the value, otherwise the default is the same as the method name. The Braves () and Braves1 () methods implement constructor injection and set mode injection                   &nbsp ;  xml file Configuration Method <beans xmlns= "Http://www.springframework.org/schema/beans"         Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"        xmlns:context= "/http Www.springframework.org/schema/context "       xsi:schemalocation="/http www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/ spring-beans.xsd        http://www.springframework.org/schema/context http:// Www.springframework.org/schema/context/spring-context.xsd ">     <context:component-scan  base-package= "Com.springapp.mvc"/>     <bean class= " Com.springapp.mvc.easyBean.Sword " id=" Sword "></bean>    <bean class=" Com.springapp.mvc.easyBean.Braves " id=" Braves ">        <constructor-arg ref=" Sword "></constructor-arg>    </bean>    <bean class=" Com.springapp.mvc.easyBean.Braves " id=" braves1 ">        <property name=" Sword "  ref= "Sword" ></property>    </bean>     <bean class= " Org.springframework.web.servlet.view.InternalResourceViewResolver ">        <property  name= "prefix"  value= "/web-inf/pages/"/>        <property name= "suffix"  value= ". jsp"/>    </bean></beans>               braves beans and  braves1 beans respectively implement constructor injection and set mode injection.
    • Java class and XML file hybrid configuration (single or multiple)
                   java class configuration package com.springapp.mvc.application;  import com.springapp.mvc.easyBean.Sword;import org.springframework.context.annotation.*;  /** * created by xuc on 2018/1/7. *  Configuration Class  */@ComponentScan ( basepackages = {"Com.springapp.mvc"}) @Configuration @import (application1.class) @ImportResource (" Classpath:mvc-dispatcher-servlet.xml ") public class application {    @Bean     Public sword sword ()  {        Return new sword ();   }} Note: Here @import annotations for the import configuration Java class, @ImportResource annotations for the import configuration XML file, where you can configure multiple, through the well-spaced               nbsp   XML file Configuration <beans xmlns= "Http://www.springframework.org/schema/beans"       &NBSP;XMLNS: Xsi= "Http://www.w3.org/2001/XMLSchema-instance"        xmlns:context= "http://www.springFramework.org/schema/context "       xsi:schemalocation=" Http://www.springframework.org/schema /beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd ">     <context:component-scan base-package=" Com.springapp.mvc "/>      <import resource= "Mvc-dispatcher-servlet1.xml" ></import>    < bean class= "Com.springapp.mvc.application.Application" ></bean>     <bean  class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >        < Property name= "prefix"  value= "/web-inf/pages/"/>        <property name= " Suffix " value=". jsp "/>    </bean></beans>       Conditional configuration
    •  spring profile for cross-environment configuration
                    1. Configure profile bean          & nbsp    java class configuration Package com.springapp.mvc.application; import ...  /** * created  by xuc on 2018/1/7. *  Configuration Class  */@ComponentScan (basepackages = {" Com.springapp.mvc "}) @Configurationpublic  class Application {    @Bean     Public  braves braves (iarms arms) {        return new braves (arms);   }    @Bean     @Profile ("Dev")     Public sword sword ()  {        Return new sword ();   }    @Bean     @Profile ("test")     Public machete machete () {        Return new machete ();   }}              NOTE: Use @profile annotations to declare which environment the bean belongs to (commonFor database connection operations)                xml file Configuration <beans xmlns= "/http Www.springframework.org/schema/beans "       xmlns:xsi=" http://www.w3.org/2001/ Xmlschema-instance "       xmlns:context=" Http://www.springframework.org/schema/context "       xsi:schemalocation= "http://www.springframework.org/schema/beans        HTTP ://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org /schema/context http://www.springframework.org/schema/context/spring-context.xsd ">     <context:component-scan base-package= "Com.springapp.mvc"/>     <beans profile= "Dev" >        <bean class= "Com.springapp.mvc.easyBean.Sword" ></bean>    </beans>    <beans profile= "test" >        &LT;BEAN&NBSP;CLass= "Com.springapp.mvc.easyBean.Machete" ></bean>    </beans>     <beans >        <bean class= " Org.springframework.web.servlet.view.InternalResourceViewResolver ">            < Property name= "prefix"  value= "/web-inf/pages/"/>            <property  name= "suffix"  value= ". JSP"/>        </bean>    </beans></ beans>                    2. Activate Spring profile<web-app version = "2.4"    xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE"  xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "   xsi:schemalocation=" http://java.sun.com/xml/ns/j2ee    http:// Java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ">    <display-name>Spring MVC  application</display-name>   &NBSP;&Lt;context-param>      <param-name>spring.profiles.default</param-name>      <param-value>dev</param-value>   </context-param>    <servlet>       <servlet-name>mvc-dispatcher</servlet-name>      <servlet-class >org.springframework.web.servlet.DispatcherServlet</servlet-class>      <init-param >         <param-name>spring.profiles.default</param-name>         <param-value>dev</param-value>      </init-param>    & nbsp   <load-on-startup>1</load-on-startup>   </servlet>    < servlet-mapping>      <servlet-name>mvc-dispatcher</servlet-name>      <url-pattern>/</url-pattern>  &NBSP;&LT;/SERVLET-MAPPING&GT;&LT;/WEB-APP&Gt;                Note: In Web Apps, just configure Spring.profiles.default or Spring.profiles.active, the former is the default which is active                     3. Test   &NBSP ;             in the case of "dev", there will only be sword beans, and using the machete bean will report the Class no exception!
    • Condition Implementing a conditional registration bean
                    Define a class that implements the condition interface, implements the matches () method, and verifies the validation in the method Packag E com.springapp.mvc.application; import org.springframework.context.annotation.condition;import  org.springframework.context.annotation.ConditionContext;import  org.springframework.core.env.environment;import org.springframework.core.type.annotatedtypemetadata;  /** * Created by xuc on 2018/1/7. *  condition determine if bean is creating  */public  class AppCondition implements Condition {    @Override     Public  boolean matches (conditioncontext conditioncontext, annotatedtypemetadata  Annotatedtypemetadata)  {        environment environment =  Conditioncontext.getenvironment ();        if  (environment.acceptsprofiles ("dev")  | |  environment.acceptsprofiles ("test")) {    &NBSP;       return true;       }        return false;  &N Bsp }}                    NOTE: @profile Note The value check is implemented through condition, Profilecondition for its implementation class as follows:  @Retention (retentionpolicy.runtime) @Target ({elementtype.type,  Elementtype.method}) @Documented @conditional (profilecondition.class) public  @interface  profile {     /**    * the set of profiles for which the  annotated component should be registered.    */   String[] value ();  } class ProfileCondition implements Condition {     @Override    public boolean matches (conditioncontext context, annotatedtypemetadata  Metadata)  {      if  (context.getenvironment ()  != null)  {      &nbsp  multivaluemap<string, object> attrs = metadata.getallannotationattributes ( Profile.class.getName ());         if  (attrs != null)  {            for  (Object value : attrs.get ("value"))  {               if  (Context.getenvironment () Acceptsprofiles (((string[))  value))  {                  return true;               }           }            Return fals e;         }     }      return true;   } }
    • Bean Injection ambiguity problem
                    1. Add @primary annotation to the bean to be injected, declaring that the bean is a priority injection package  com.springapp.mvc.application; import com.springapp.mvc.easybean.braves;import  com.springapp.mvc.easybean.iarms;import com.springapp.mvc.easybean.machete;import  com.springapp.mvc.easybean.sword;import org.springframework.context.annotation.*; /** *  created by xuc on 2018/1/7. *  Configuration Class  */@ComponentScan (basepackages =  {"Com.springapp.mvc"}) @Configurationpublic  class Application {    @Bean     @Conditional (appcondition.class)     public braves braves (iarms arms) {        return new braves (arms);   }    @Bean     @Profile ("Dev")   & nbsp @Primary     Public sword sword ()  {        Return new sword ();    }&NBSp   @Bean     @Profile ("test")     Public machete machete () {        Return new machete ();   }}                  &NBSP;&NBSP ;                   2. Add @qualifier annotations to injected beans package  com.springapp.mvc.application; import com.springapp.mvc.easybean.braves;import  com.springapp.mvc.easybean.iarms;import com.springapp.mvc.easybean.machete;import  Com.springapp.mvc.easybean.sword;import org.springframework.beans.factory.annotation.qualifier;import  org.springframework.context.annotation.*; /** * Created by xuc on  2018/1/7. *  Configuration Class  */@ComponentScan (basepackages = {"COM.SPRINGAPP.MVC"}) @ configurationpublic class application {    @Bean     @Qualifier ("sword")     Public braves braves (IARMS&NBsp;arms) {        return new braves (arms);   }    @Bean     @ Profile ("Dev")     Public sword sword ()  {        return new  Sword ();   }    @Bean     @Profile ("test")     Public machete machete () {        Return new machete ();   }}            &N Bsp       NOTE: If there are multiple (that is, multiple priority) here, you can customize the annotations
    • Scope of the Bean
Scope Describe
Singleton This scope restricts the definition of the bean to a single instance of each Spring IoC container (the default).
Prototype This scope restricts the definition of a single bean to any number of object instances.
Request This scope restricts the bean's definition to an HTTP request. Valid only in the context of Web-aware Spring ApplicationContext.
Session This scope restricts the bean's definition to an HTTP session. Valid only in the context of Web-aware Spring ApplicationContext.
Global-session This scope restricts the bean's definition to a global HTTP session. Valid only in the context of Web-aware Spring ApplicationContext.
 package com.springapp.mvc.application; import com.springapp.mvc.easybean.braves;import  com.springapp.mvc.easyBean.IArms;import com.springapp.mvc.easyBean.Machete;import  Com.springapp.mvc.easybean.sword;import org.springframework.beans.factory.annotation.qualifier;import  org.springframework.context.annotation.*;import  Org.springframework.web.context.webapplicationcontext; /** * created by xuc on  2018/1/7. *  Configuration Class  */@ComponentScan (basepackages = {"COM.SPRINGAPP.MVC"}) @ configurationpublic class application {    @Bean     public braves  Braves (iarms arms) {        return new braves (arms);   }    @ bean    @Profile ("Dev")     @Scope (value = webapplicationcontext.scope_global_session ,            PROXYMODE&NBSP;=&NBSP;SCOPEDPROXYMODE.target_class)     Public sword sword ()  {        return new  Sword ();   }    @Bean     @Profile ("test")     Public machete machete () {        Return new machete ();   }}            &N Bsp   Note: The Sword bean is redefined here through @scope annotations as a session-level scope, because sword is loaded as a priority when using Braves, and the Proxymode claims proxy class,          is to inject the session-level sword into a single-class Braves by the form of deferred injection. If this is the interface: "Proxymode = scopedproxymode.interfaces"  github Address: Https://github.com/xc83415134/spring_bean_demo    environment: Idea, Spring4.0 reference: "Spring Combat"            

Spring Use Tour (i)----Bean Assembly

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.