1.service接口
package spring.service;
public interface Service {
public void do_some();
}
2.实现类
package spring.service;
public class ServiceImp implements Service{
@Override
public void do_some() {
System.out.println("你好,spring");
}
}
3.静态工厂
package spring.service;
public class Service_fatory1 {
public static ServiceImp getService(){
return new ServiceImp();
}
}
4.实例工厂
package spring.service;
public class Service_fatory2 {
public ServiceImp getService(){
return new ServiceImp();
}
}
4。bean.xml配置
<?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的三种方式-->
<!--第一种,普通方式-->
<bean id="service" class="spring.service.ServiceImp"></bean>
<!--第二种,静态工厂-->
<bean id="service2" class="spring.service.Service_fatory1" factory-method="getService"></bean>
<!--第三种方式,实例工厂-->
<!--首先创造工厂bean-->
<bean id="fatory2" class="spring.service.Service_fatory2"></bean>
<!--创建一个索引去调用实例方法-->
<bean id="service3" factory-bean="fatory2" factory-method="getService"></bean>
</beans>
5.测试类
package spring.test;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import spring.service.Service;
public class test {
@Test
public void test(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Service service= (Service) context.getBean("service");
Service service1= (Service) context.getBean("service2");
Service service2= (Service) context.getBean("service3");
service.do_some();
service1.do_some();
service2.do_some();
}
}
6.结果完美
7.感想
(1)不要害怕报错,努力去读logging
(2)事实上就是复习了工厂模式罢了