Spring IOC Common explanations

Source: Internet
Author: User

[TOC]

Spring container

When you configure an object, the default singleton
The scope property of the bean can be set

    1. Singleton Singleton mode, only the bean is created when the IOC container is initialized and is created only once
    2. Prototype prototype mode, the Bean is created every time the bean is fetched, and a new object is created each time it gets
    3. Session share one bean per conversation
    4. Request to share a bean each
How to configure
    • Configuration by property name corresponding to the property value
    • Configuration through the construction of a class
    • Can be configured by (ref) reference when a JavaBean contains properties for the image
    • List,map,set
<LIST>    bean=   />  </LIST>  <SET>  <ref   bean=   "Beanid"  />  </SET>     <MAP>  <entry   key=   "AA"   value-ref=   "B1"     />  <entry   key=   "BB"   value-ref=   "B2"  />  </MAP>   
    • Bean Auto Configuration
      Automatic configuration of Bran can be achieved by autowire
      1. Autowire= "ByName" requires that the property name is the same as the ID of the object bean
      2. Autowire= "Bytype" requires that the type of the Property object to be automatically configured is consistent with the type of the property and unique
    • Configure Properties

      <property name="properties"><props>    <prop key="driverClassName">oracle.jdbc.driver.OracleDriver</prop>    <prop key="url">jdbc:oracle:thin:@127.0.0.1:1521:XE</prop></props></property>
Annotation configuration
<context:component-scan base-package="com.yuing.spring1"/><!--开启自动扫描组建-->
    • @Component arbitrary Java Classes
    • @Controller Control Layer
    • @Repository DAO Layer
    • @Service Business Layer

Configure filters

    • Exclude-filter does not contain filter conditions
    • Include-filter contains filter conditions (the default filter should be turned off first when used use-default-filters="false" )
    • There are five types of type
AspectJ assignable Custom Regex annotation filtering based on annotations
Org.springframework.stereotype.Component//@Component (any one class)
Org.springframework.stereotype.Repository//@Repository
Org.springframework.stereotype.Service//@Service
Org.springframework.stereotype.Controller//@Controller

Auto-injection: @Autowire label on an object returns an object in a container

<context:component-scan base-package="包名">    <context:exclude-filter type="过滤的条件类型" expression="条件"/></context:component-scan><context:component-scan base-package="包名" use-default-filters="false">    <context:include-filter type="过滤的条件类型" expression="条件"/></context:component-scan>
To set a special value for a Bean's properties
    • Set the special string "<", ">"

      <!-- 在value标签中的<![CDATA[value]]> 中设置属性的值 --><property name="propertyName"><value><![CDATA[<Java开发>]]></value></property>
    • Set empty

<property name="propertyName">    <null/></property>
Label Properties
    • Bean Label Configuration JavaBean Object
    • Util label Declaration (list,map,set,property)
    • P Tag Bean label attribute P: Property name = "attribute value"
    • Context tag Load External file

    • Abstract: When the bean's abstract property is set to True, the bean can only be used as a template bean and not be initialized by the container.

      The child bean loads the template by parent= "Beanid"

Bean's life cycle

Classpathxmlapplicationcontext The Bean is created when the container is initialized Classpathxmlapplicationcontext The bean is destroyed when it is destroyed.
Bean's Properties

init-method= "" : You can specify the initialization method that executes a bean object when the bean is loaded successfully

destroy-method= "" : You can specify how to execute a destroy in a bean object when the bean is about to be destroyed

Configure the value of the Druid Connection pool load properties file call
    • Load Properties File
 <context:property-placeholder location="classpath:db.properties"/>
<beanclass="Com.alibaba.druid.pool.DruidDataSource"id="DataSource">    <propertyname="username"value="${username}"/>    <propertyname="Password"value="${password}"/>    <propertyname="url"value="${url}"/>    <propertyname="Driverclassname"value="${driverclassname}"/></bean>
Expression language of spel:spring
#{beanId}                  引用其他的bean对象#{beanId.pro}              引用其他bean对象的属性值 #{beanId.methodName()}     调用方法得到返回值#{田间 ? ‘真的返回值‘ : ‘假返回值‘}      三目运算
Factory Bean (Factorybean
public class CarFactoryBean implements FactoryBean<Car> {} //以Car类为例
    • How to configure
<bean id="car" class="com.hwua.spring02.factory.CarFactoryBean"/>
Bean Post Processor (executed before and after initialization)

Configuration:

 <bean class="com.hwua.spring02.util.MyPostProcessor"/>

Java code:

 Public classMypostprocessorImplementsBeanpostprocessor {@Override     PublicObjectpostprocessbeforeinitialization(Object O, String s)throws     //Parameter O:bean object S:bean IDbeansexception {System. out.println("Mypostprocessor.before:"+o+", S:"+s);if(OinstanceofBook) {//Is book}Else if(OinstanceofCar) {//Is car}returnO }@Override     PublicObjectpostprocessafterinitialization(Object O, String s)throwsbeansexception {System. out.println("Mypostprocessor.after:"-om", S:"+s);returnO }}
Configuration of the Java factory Class (understanding)

Java code

 Public classstaticcarfactory {Private StaticMap<string,car> Carmap =NewHashmap<> ();Static{Car BMW =New Car(); bmw.Setbrand("BMW"); bmw.Setprice(9.9); Car Audi =New Car(); Audi.Setbrand("Audi"); Audi.Setprice(19.9); Carmap.put("BMW", BMW); Carmap.put("Audi", Audi); } Public StaticCarCreatecar(String brand) {returnCarmap.Get(brand); }}

XML code

<!--static Factory creation objects do not require an instance of chemical plant class --<beanid="Car"class="Com.hwua.spring02.factory.StaticCarFactory"factory-method="Createcar">    <constructor-arg [name= "parameter name"]value="Audi"/></bean><!--instance factories need to first instance chemical plant<beanid="Carfactory"class="Com.hwua.spring02.factory.InstanceCarFactory"/><!--to create car objects using the factory class --<beanid="Car1"factory-bean="Carfactory"factory-method="Createcar">    <constructor-arg [name= "parameter name"]value="Audi"/></bean>
Used in the Java class:
newClassPathXmlApplicationContext("applicationContext.xml");//创建容器的对象ac.getBean(Class<T>|"IdString");//获取javaBean对象 当一个类配置了多个javabean时通过类和id可以锁定一个JavaBean
@Autowired      //自动装配(默认是根据class)@Qualifier("bookServer")    //根据id进行装配BookServer bookServer;
Instance
<?xmlVersion= "1.0" encoding= "UTF-8"?><beansxmlns="Http://www.springframework.org/schema/beans"xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >    <beanid="Person1"class="Com.yuing.spring1.User">        <propertyname="Age"value=" "/>        <propertyname="Name"value="Zhang San"/>        <propertyname="book"ref="B1"/>        <propertyname="Book.name"value="Oracle Foundation"/>        <propertyname="Book.price"value="99.8"/>    </bean>    <!--simple javabean-->    <beanid="Person2"class="Com.yuing.spring1.User">        <constructor-argvalue="John Doe"name="Name"/>        <constructor-argvalue="a"name="Age"/>    </bean>    <beanid="Person3"class="Com.yuing.spring1.User">        <constructor-argvalue="John Doe"index="0"/>        <constructor-argvalue="a"index="1"/>    </bean>    <beanid="B1"class="Com.yuing.spring1.pojo.Book">        <propertyname="Name"value="Java Basics"/>        <propertyname="Price"value="3.5"/>    </bean></beans>

Spring IOC Common explanation

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.