spring实例化bean三种方式

我看了这篇博文《https://www.cnblogs.com/zhanglei93/p/6221546.html》,以及自己实践总结了关于spring实例化bean对象的3种方式。

一、通过构造

  1.1通过无参构造:

    在加载applicationContext.xml文件的时候会通过无参构造实例化对象。

  applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans 
	<!--约束省略-->


<!-- 配置service -->

<bean id="userService" class="com.xx.service.UserServiceImpl" />

</beans>

   需要被spring管理的类

package com.xx.service;

public class UserServiceImpl implements UserService{

	public void run(){
		System.out.println("userService is running");
	}
	public UserServiceImpl(){
		System.out.println("no param");
	}
}

1.2通过有参构造:

 在加载applicationContext.xml文件的时候会通过有参构造实例化对象。

applicationContext.xml

此处index表示构造里的参数,从0开始,value是形参的值

<?xml version="1.0" encoding="UTF-8"?>
<beans 
    <!--约束省略-->
<!-- 配置service -->
<bean id="userService" class="com.xx.service.UserServiceImpl">
<constructor-arg index="0" value="rose"/>
<constructor-arg index="1" value="mark"/>
</bean>
</beans>

 需要被spring管理的类

rose和mark会被当做形式参数将值传递给str和str1,从而完成实例化对象

package com.xx.service;

public class UserServiceImpl implements UserService{
	public void run(){
		System.out.println("userService is running");
	}
	public UserServiceImpl(String str,String str1){
		System.out.println(str);
		System.out.println(str1);
	}
}

 二、通过静态工厂

applicationContext.xml文件

factory-method是class下的静态方法,意味着执行此方法从而得到实例化的对象

<?xml version="1.0" encoding="UTF-8"?>
<beans 
    《!--约束省略--》

<bean id="userServiceByFactory" class="com.xx.factory.BeanFactory" factory-method="createUserService"/>

</beans>

生产实例化工厂

package com.xx.factory;

import com.xx.service.UserService;
import com.xx.service.UserServiceImpl;

public class BeanFactory {
	
	public static UserService createUserService(){
		return new UserServiceImpl();
	}
}

三、通过实例(非静态)工厂

applicationContext.xml

指定哪个类,哪个方法,从而返回实例化对象

<?xml version="1.0" encoding="UTF-8"?>
<beans 
	<!--约束省略-->

<bean id="beanFactory" class="com.xx.factory.BeanFactory"/>
<bean id="userService" factory-bean="beanFactory" factory-method="createUserService"/>

</beans>

  实例工厂

package com.xx.factory;

import com.xx.service.UserService;
import com.xx.service.UserServiceImpl;

public class BeanFactory {
	
	public UserService createUserService(){
		return new UserServiceImpl();
	}
	
}

以上三种方式的测试方法:

package com.xx.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.xx.service.UserService;
public class UserServiceTest {
	private ApplicationContext context = null;
	@Test
	public void TestApp() {
		String beanPath="classpath:applicationContext.xml";
		context = new ClassPathXmlApplicationContext(beanPath);
		UserService userService = (UserService) context.getBean("userService");
		userService.run();
	}
}

 

总结:提倡使用无参构造实例化。

非静态

Best Regards
原文地址:https://www.cnblogs.com/pecool/p/8231907.html