spring bean 构造方法实例化

版权声明:本文为博主原创文章,欢迎指正或者转载。 https://blog.csdn.net/ThinkPet/article/details/83046259

spring框架实例化bean有3中方式,即构造方法实例化静态工厂实例化实例工厂实例化(其中,最常用的是构造方法实例化)

构造方法实例化

spring容器可以调用bean对应类中的无参数构造方法来实例化bean,这种方式称为构造方法实例化

1.创建web应用,并导入依赖的jar包

2.创建beanClass类

package instance;

public class BeanClass {

	public String message;

	public BeanClass(String s) {
		
		this.message = s;
	}

	public BeanClass() {
		this.message="构造方法实例化bean";
	}
	
}

3.创建配置文件

<?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.xsd">

    <bean id="constructorInstance" class="instance.BeanClass">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    

</beans>

4.创建测试类

package test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import instance.BeanClass;

public class TestInstance {
	public static void main(String[] args) {
		ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		BeanClass b1 = (BeanClass)appCon.getBean("constructorInstance");
		System.out.println(b1+b1.message);
	}
}

猜你喜欢

转载自blog.csdn.net/ThinkPet/article/details/83046259