Spring有三种实例化Bean的方式

一.构造器注入实例化

  前面一个帖子的实现就是用构造器实现,也是最普遍用到的一种,在此不过多的描述。

  <bean ></bean>

二.使用静态工厂方法实例化

PersonServiceFactory :
package cn.service.impl;

public class PersonServiceFactory {
	
	public static PersonServiceImpl createPersonServiceImpl(){
		return new PersonServiceImpl();
	}
}
---------------------------------------------------------------
<?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">
	
		<bean ></bean>
		
</beans>
---------------------------------------------------------------
package junit.test;

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

import commons.tz.TzClassPathXmlApplicationContext;

import cn.service.PersonService;

public class Spring02Test {

	@Test
	public void instanceSping() {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		PersonService personService = (PersonService) ctx.getBean("personService");
		personService.save();
	}
}

三.使用实例工厂方法实例化

PersonServiceFactory :
package cn.service.impl;

public class PersonServiceFactory {
	
	public PersonServiceImpl createPersonServiceImpl(){
		return new PersonServiceImpl();
	}
}
-------------------------------------------------------------------------
<?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">
	
		<bean ></bean>
		<bean ></bean>
		
</beans>
-------------------------------------------------------------------------
package junit.test;

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

import commons.tz.TzClassPathXmlApplicationContext;

import cn.service.PersonService;

public class Spring02Test {

	@Test
	public void instanceSping() {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		PersonService personService = (PersonService) ctx.getBean("personService");
		personService.save();
	}
}

今天学的不多,偷个懒!

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-03
  • 2021-11-13
  • 2021-11-02
  • 2021-04-04
  • 2021-11-29
相关资源
相似解决方案