2. Three Methods for Spring IoC to instantiate bean, 2. springiocbean

Source: Internet
Author: User

2. Three Methods for Spring IoC to instantiate bean, 2. springiocbean

1. Constructor

That is, in the example mentioned in the previous article, the default no-argument constructor is called.

2. Static factory Method

1) create a class for the method to be executed

public class HelloWorld {public HelloWorld(){System.out.println("aaaa");}public void hello(){System.out.println("hello world");}}

2) create a static Factory

public class HelloWorldFactory {public static HelloWorld getInstance(){return new HelloWorld();}}

3) Compile the applicationContext. xml configuration file.

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "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-2.5.xsd"> <! -- In this configuration, the spring container uses the default constructor to create an object for HelloWorld --> <bean id = "helloWorld" class = "HelloWorld"> </bean> <! -- Use the static factory method to create an object factory-method as the factory method --> <bean id = "helloWorld2" class = "HelloWorldFactory" factory-method = "getInstance"> </bean> </beans>

4) Start the container, create an object, and call the method.

@Testpublic void test(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");HelloWorld world = (HelloWorld)context.getBean("helloWorld2");world.hello();}

3. instance factory method (omitted)

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.