IOC container-managed bean Spring in the scope of the bean

IOC container-managed bean 
Bean name and instantiate method 
Bean naming 

each Spring to the IOC (collectively, behind the Spring container) container object is created must be assigned at least one name, if the developer does not provide, Spring container will assign an internal name, by the name of Bean, we can find in other classes in the class and use it, as in the previous case, the name is Bean get to the actual object and perform the corresponding operations by. In the configuration xml-based, you can use the id attribute to Bean assign names to a, in the same xml configuration file, id must be unique, but different xml can be the same, of course, you can also use the name you give Bean assign a name , name attribute can be assigned a plurality of names, then you can use spaces, commas, semicolons to separate names given Bean assign a plurality, and the id attribute can not be used as such. 

<-! Name attribute plurality name -> 
<the bean name = "AccountDao, accountDao2" class = "com.zejian.spring.springIoc.dao.impl.AccountDaoImpl" /> 
<-! Configuration unique ID attribute name but not the same name -> 
<the bean ID = "accountDaoId" class = "com.zejian.spring.springIoc.dao.impl.AccountDaoImpl" /> 

 

declares two names in the name attribute in addition to the first name other names are called aliases (aliase). In addition to defining the Bean name, but also the use of <alias> tag aliased to Bean: 

<the bean ID = "accountDaoId" 
! <- name attribute specifies give the Bean given an alias, 
<Alias name = "accountDaoId" Alias = "accountDao3" /> 

 

Obviously Bean object if we want to configure already exists, and want to give special names to some of the Bean, alias at this time is quite useful. Bean object using the above statements are statements manually declared in the xml way, once the object multiplied Bean, Bean could manage cumbersome happens, in order to provide a Spring configuration based on Java annotations, the following were used org.springframework.stereotype .Service (@Service) and org.springframework.stereotype.Repository (@Repository) statement AccountServiceImpl and AccountDaoImpl class, use @Autowired annotation injection accountDao (Footnote drive on the xml declaration) 

// @ the Component same effect 
@Service 
public class AccountServiceImpl the implements {the AccountService 
  @Autowired 
  Private AccountDao AccountDao; 
} 

 

// @ same effects as the Component 
@Repository 
public class AccountDaoImpl the implements AccountDao { 
// ...... 
}

With annotation statement, we do not need more than two declared xml Bean, but need to clearly tell Spring Bean annotated in those packages, you need to add packet scanning mechanism, then you need to enable the Spring context namespace:
<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.zejian.spring.springIoc" /> </beans>

The above statement in the same way as before the effect of xml declaration bean. Here we need to understand that you can use annotations to achieve the effect @Component @Service and @Repository, Meaning @ Component and @Service did not differ, but @Service also allows us to understand the class to business class only. As @Repository can also enable other functions to access data related to the chain with Spring represents a data access layer, while the meaning of (this again dwell in the Spring jdbc-related content, and this time we just need to understand @Repository equivalent to @Component ), you can also enter the name of a String value to the @ Component, @ Service and @Repository, if the name is not provided, then the default is a simple class name (first character lowercase) becomes Bean name.

@Service("accountService")
public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; } @Repository("accountDao") public class AccountDaoImpl implements AccountDao{ //...... }

 

So to this we also know, the Spring framework provides the equivalent of three @Component annotation notes, @ Repository for DAO implementation class tagging, @ Service for Service implementation class tagging, @ Controller controller implementation class for tagging (web layer controller), and an understanding of the objects bean Spring container configured through java bean and annotation tag xml declaration in two ways, we can also be used alone or mixture of two one use, depending on their needs.

 


 Bean rewriting mechanism

 

Bean rewrite mechanism is not so mysterious, mainly as a priority issue when reading the bean id attribute of the same name appear different xml file, the same simple look at an example to understand. Define two spring profile and simultaneously loads them: Spring - ioc.xml

 <Beans xmlns = "http://www.springframework.org/schema/beans" 
  xmlns: the 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: // the WWW. springframework.org/schema/beans/spring-beans.xsd 
HTTP: // www.springframework.org/schema/context 
HTTP: // www.springframework.org/schema/context/spring-context.xsd 
"> 
<-! - The default constructor is created and injected into the property's value property -> 
<bean the above mentioned id = "account"="com.zejian.spring.springIoc.pojo.Account" >
    <property name="name" value="I am SpringIOC1" />
    <property name="pwd" value="123" />
</bean>
</beans>

 

spring-ioc2.xml

<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 
"> 
<- default constructor is created and injected into the property's value Property ->! 
<bean the above mentioned id =" the Account " class =" COM. zejian.spring.springIoc.pojo.Account "> 
    <Property name =" name "value =" the I AM SpringIOC2 "/> 
    <Property name =" pwd "value =" 123 "/> 
</ the bean> 
</ Beans>

Get bean and calls

@Test
public void test1() { ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring/spring-ioc.xml","spring/spring-ioc2.xml"); Account account= (Account) applicationContext.getBean("account"); System.out.println("调用结果:"+account.getName()); }

 

 

Apparently the same name in different id xml configuration file and declare the same type of bean object, spring containers will be loaded by default spring-ioc2.xml last added in the account but ignored spring-ioc.xml in the account, that is, bean said rewriting mechanism principle is the same as when you declare the name of the bean, which will cover the former. We also need to be clear that when, in the web application development process, usually the hierarchical configuration management, then it is polymerized by a master springApplication.xml, hierarchical configuration files belonging to springApplication.xml in this case subfolders, such a relationship in priority encounter this situation generally subfolder high, so the child file loads the bean. As introduced in the subfile spring-ioc2.xml spring-ioc.xml master file:

<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 "> <!-- 默认构造创建,并通过property 注入属性值 --> <bean id="account" class="com.zejian.spring.springIoc.pojo.Account" > <property name="name" value="I am SpringIOC1" /> <property name="pwd" value="123" /> </bean> <!-- 导入的子文件 --> <import resource="spring-ioc2.xml" /> </beans>

 

Run the code:

@Test
  public void test1() { ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring/spring-ioc.xml"); Account account= (Account) applicationContext.getBean("account"); System.out.println("调用结果:"+account.getName()); }

 

The code will be loaded first spring-ioc2.xml the spring-ioc.xml account and ignore the account, the same effect as the previous code.

 

 

 

Spring in the scope of the bean

 When creating a Bean instance Spring IOC container, for instance to specify the scope Bean, including the scope singleton (singleton), the prototype (prototype patterns), request (HTTP request), the session (session), global-session (Global session).

 

 Bean prolonged load

 

 

In some cases, we may want to use the bean to create a delay stage, in order to avoid unnecessary memory consumption, Spring also voluntarily support the initialization delay bean. It is possible to define lazy loading the bean in the configuration file, bean actually created until Spring when needed to create such a container will be delayed. Under normal circumstances, have been created from a bean reference to another bean, or show to find a bean bean that trigger the creation of a delay even if the configuration properties, so creating a bean instance is set to extend those loaded at startup if the Spring container, Not surprisingly, those bean may delay initialization may be injected into a non-delayed and create scope for a singleton bean. Use the bean lazy-init attribute in the xml file can be configured to change the bean whether lazy loading, if you need to configure bean whole xml files are lazy loading using defualt-lazy-init attribute, please note that lazy-init attribute overrides defualt-lazy -init property.

 

<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
        " default-lazy-init="true">
    <!--default-lazy-init="true "xml bean in all lazy loading ->
    <-! Lazy-init = " false" represents a non-extended loading -> 
    <the bean name = "AccountDao" the lazy-the init = "to false" class = "com.zejian.spring.springIoc.dao.impl.AccountDaoImpl" / > 
    <! - declare accountService objects, to create a spring -> 
    <bean name = "accountService" class = "com.zejian.spring.springIoc.service.impl.AccountServiceImpl"> 
          <! - injected accountDao object, you need The method set -> 
          <Property name = "AccountDao" REF = "AccountDao" /> 
    </ the bean> 
</ Beans>
          

 

Spring container will be created by default in the start-up phase bean, a process called pre-bean initialization, this is good, can be found as early as possible typos configuration errors occur, such as configuration files, or some bean has not yet been defined It was injected and so on. Of course, as there is a lot of bean needs to be initialized, which may cause a slow start spring container, certain bean may just need some occasions but did not need to create a container in the spring start-up phase, this may be Mybatis of bean or Hibernate SessionFactory SessionFactory etc. delayed load them will start Spring container is more relaxed, thus reducing unnecessary memory consumption.

<context:component-scan/>与<context:annotation-config/>

When we use with the foregoing @ Autowired, @ Resource, @ Value assembling such as automatic annotation <context: annotation-config /> annotation-driven register, so that the annotation effect. In fact, such <context: annotation-config /> a configuration, it is the role of formula register AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor and RequiredAnnotationBeanPostProcessor to four BeanPostProcessor Spring container. After four register BeanPostProcessor Spring container can identify the corresponding annotated, of course, they can also be individually configured. 
If you want to use the @ Resource, @ PostConstruct, @ PreDestroy and other annotations can be declared separately CommonAnnotationBeanPostProcessor 
Bean If you want to use @PersistenceContext notes, the statement PersistenceAnnotationBeanPostProcessor. 
If you want to use annotations @Required, you must declare RequiredAnnotationBeanPostProcessor of Bean. 
In general, these notes are everywhere, if you always need a configuration of a naturally very cumbersome, so spring container very intelligent delivery <context: annotation-config /> for our simplified configuration, automatically declared. 
For <context: component-scan />, the front when using @ Service, @ Component, @ Controller, @ Repository other annotations need xml configuration file declares packet scan driver <context: component-scan />, its role is Spring container startup will start to scan the corresponding annotation-driven bean object in the package and create instances of them, so we can not be carried out one by one declared bean configuration, which greatly simplifies the programming code. Note that when spring xml configuration file the <context: component-scan /> after, <context: annotation-config /> can retire, because <context: component-scan /> already contains a <context: annotation -config /> function of. In most cases, are used as <context: component-scan /> registration and annotation-driven scan function packages.

 

Guess you like

Origin www.cnblogs.com/hellohero55/p/12649993.html