Spring (2) Bean entry, Spring Bean entry

Source: Internet
Author: User

Spring (2) Bean entry, Spring Bean entry
1. BeanFactory Introduction1.1. Bean:

  • In Spring technology, it is component-based.
  • The most basic unit is the most commonly used unit.
  • In fact, the instance is saved in the Spring container.

Bean is usually defined in the configuration file. Bean instantiation is managed by the Spring Ioc container, and Bean instances can be accessed through Beanfactory. In fact, most J2EE applications, bean is accessed through ApplicationContext. ApplicationContext is a sub-interface of BeanFactory, which is much more powerful than BeanFactory.

1.2 roles of BeanFactory
  • Configure, create, and manage Bean objects
  • Maintain the dependency between Bean objects
  • Responsible for Bean object Lifecycle

BeanFactory common methods:

  • ContainsBean (String beanname)
  • Object getBean (String beanName)

The XmlBeanFactory class is usually used for implementation.

1.3 ApplicationContext
  • Read Bean definition files
  • Maintain dependencies between beans
  • International support
  • The getRource () method for reading resource files allows you to easily read Rource objects.
  • Event Propagation
  • Load multiple configuration files

 

Ii. Bean definition 2.1, basic components

Configuration File

  • <Beans/> is the root node of the Sring configuration file.
  • A <beans/> node can contain multiple <bean> nodes.

When defining a <bean> node, you must specify two attributes.

Id: identifies the bean. This identifier is unique. Spring requires this attribute for bean management and dependency between beans.

Class: Specifies the specific implementation class of the bean. Here it cannot be the full path package name of the interface (which can be the interface implementation class). class Name

Bean in Spring container (Use scope to set the default value not to singelton)

Singleton: single-instance mode (default, the constructor is private). Only one shared instance exists in the entire Spring container (Singleton)

Non-singelton: each time the bean is requested, a new bean instance is created in the Spring container and then returned to the Program (request, session, prototype)

2.2 create Bean

Bean Name:

Follow the naming rules in Java and use clear, descriptive, and consistent naming rules.

Bean naming mechanism:

Id: when you search for a Bean object in the Spring window, you first search for the Bean object based on the id and use the rest as the default Bean name. If the ID attribute does not exist, search by Name attribute (use the first NAME as the default Name). If neither ID nor NAME exists, search by class Name.

Id ----------> name ---------------> Class name

<Bean id = "id1" class = "implementation class"> </bean> <bean name = "id1" class = "implementation class"> </bean> <bean class = "implementation class"> </bean>

Bean alias:

Use the alias attribute to specify:

<Alias name = "specify the name of the associated Bean fromname" alias = "name of the alias of the associated class toname"/>
2.3 create a Bean

Create XML file ---- write configuration information --- generate Bean class ---- add Bean to configuration file

Iii. Bean injection 3.1, basic type, and String
  • Use Value Element
  • The XML Parser parses data of the String type.

If the property is not of the String type, the property value is converted to another type through PropertyEditors.

3.2 inject Bean

-Ref element for identification

The Ref element usually has two attributes:

Bean: specifies the bean id that is not in the same XML file.

<Bean id = "test" class = "com. pb. test "> <property name =" user "> <ref bean =" id of another bean "/> </property> </bean>

Local: Specifies the bean id in the same XML file.

<Bean id = "test" class = "com. pb. test "> <property name =" user "> <ref bean =" bean id in the same XML file "/> </property> </bean>

Differences between value and ref:

Using the ref element, Spring can verify whether the dependent Bean actually exists during deployment.

Specifying the value element only performs verification when the Bean instance is created. This will cause an error delay and lead to additional type conversion overhead.

3.3. Set Injection

List:

<bean id="test" class="com.pb.test">        <property name="lists">        <list>        <value>1</value>        <value>2</value>        <value>3</value>        </list>        </property>    </bean>

 

Map:

<bean id="test" class="com.pb.test">        <property name="map">            <map>                <entry key="key1">                    <value>value1</value>                </entry>                <entry key="key2">                    <value>key2</value>                </entry>            </map>        </property>    </bean>

 

Props:

<bean id="test" class="com.pb.test"><property name="props"><props><prop key="key1">value1</prop><prop key="key2">value2</prop></props></property></bean>

Set:

<Property name = "interest"> <set> <value> singing </value> <value> dancing </value> <value> calligraphy </value> </set> </property>

 

3.4 Automatic Binding

Set through the autowire attribute

No: default value. Not bound by default

ByName:Automatic Binding Based on attribute name

ByType: automatically bound according to the property type

Iv. Bean Scope
  • Singleton: (single-instance mode) only one shared bean instance exists in the spring container, and only the same bean instance is returned for all requests to this bean.
  • Propertype (no-singleton): A new bean instance is generated for each request to this bean. It is equivalent to the new operation in java. The bean defined as propertype has a long life cycle and is not easy to recycle. It usually needs additional processing.
  • Request: A new bean instance is generated for each http request,Bean is valid only in the current http request range.
  • Session:A new bean instance is generated for each http request,Bean is valid only in the current http session range.
5. Bean management lifecycle 5.1 and Bean Lifecycle

5.2 lifecycle management

Two opportunities

Spring can manage the behavior between instantiated beans and before they are destroyed.

After the dependency is injected:

  • Use the init-method attribute: Specify the init-method attribute to determine that a method should be executed after the Bean dependency is completed. This method does not require the code to be coupled with the Spring interface, and the code pollution is extremely small. Generally, the method definition in bean is like the init () method, and then the init-method attribute is added to the Bean element in the configuration file to implement this process.
  • Implement the InnitializingBean interface: you do not need to specify the init-method attribute in this method. After the window dependency is injected, the afterPropertiesSet method is automatically called, which performs the same effect as the init-method, however, this method is not recommended for invasive code design.

Before the Bean is destroyed:

  • Destroy-method: the method to be executed before Bean destruction is executed. This method is as stress-free as init-method.Code is coupled with Spring interfaces, and code pollution is extremely small. Add the destory-method attribute to bean and implement this process.
  • Implement the DisposeableBean interface: you do not need to specify the destory-method attribute. After container dependency injection, the destroty method is automatically called. This method is not recommended for invasive code design.
Vi. Bean inheritance

Bean inheritance:

What is Bean inheritance? Inheritance refersChild bean can inherit configuration information from parent beanIt can also overwrite specific configuration information, or add new configuration information based on the parent bean. In fact, it is similar to the inheritance relationship between child classes and parent classes in java, inheritance can save a lot of configuration work. In actual project applications, common configurations are configured as templates for child bean inheritance. If the configuration information of the two beans is roughly the same, bean inheritance can be used.Reduce Configuration.

Bean template:

In Spring, since the public configuration is to be configured as the template, thisTemplate does not need to be instantiatedInstead, it is used only as the template of the sub-bean. However, by default, all beans are initialized in ApplicationContext or BeanFactory.

Abstract attribute can be used to prevent the template from being instantiated.

Abstract = "true" indicates that the bean is an abstract bean and cannot be initialized.

 

Related Article

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.