Spring learning notes (3) -- Bean injection method, learning notes bean

Source: Internet
Author: User

Spring learning notes (3) -- Bean injection method, learning notes bean

Dependency Injection

Dependency injection supports property injection, constructor injection, and factory injection.

Property injection:

Property injection uses the setXxx () method to inject Bean property values or dependent objects.

Property injection requires Bean to provide a default constructor (no-argument constructor) and provide the corresponding Setter method for the property to be injected.

Process: Spring first calls the Bean's default constructor to instantiate the Bean object, and then calls the Setter method through reflection to inject the attribute value.

Configuration method:

<bean id="bigbean" class="com.me.Bigbean">    <property name="age"><value>25</value></property></bean>

Each attribute of Bean corresponds to each <property> in <bean>, and name is the name of the attribute. The Bean implementation class has the corresponding Setter method. (Note: Spring only checks whether the Bean has the corresponding Setter method. If the Bean has the corresponding attribute variable, no requirement is required)

 

Constructor injection:

Constructor injection ensures that some necessary attributes are set during Bean instantiation and can be used after Bean instantiation. If property injection can only be manually guaranteed during configuration, but cannot be ensured at the syntax level, constructor injection can meet this requirement well.

Requirement: Beans must provide constructors with parameters.

Configuration method:

<bean id="bigbean" class="com.me.Bigbean">
  <constructor-arg index="0" type="int">
     <value>25</value>
  </constructor-arg>
</bean>

Factory method injection:

<! -- Add later -->

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.