1010cc时时彩标准版 > 三分时时彩1010CC > 的生命周期,Bean的作用域

原标题:的生命周期,Bean的作用域

浏览次数:188 时间:2019-08-13

scope 功能域(bean 的生命周期),scopebean

图片 1

暗中同意是 singleton ,单例格局,如下代码:

 1     @Test
 2     public void testAddUser() throws Exception {
 3         ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");//初始化ApplicationContext对象,加载配置文件
 4         
 5         UserService service = (UserService)ctx.getBean("userService");//从容器中取
 6         UserService service2 = (UserService)ctx.getBean("userService");//从容器中取
 7         
 8         System.out.println(service == service2);//true
 9         
10         User u = new User();
11         u.setUsername("zhangsan");
12         u.setPassword("zhangsan");
13         service.addUser(u);//容器中已经配置了UserDAOImpl了,并把DAOImpl注入到service之中,所以service直接就可以保存了
14     }

  获取的 service 和 service2 都是一个目的,结果为true。

  假若将 scope 设置为 prototype: 1 <bean id="userService" class="com.bjsxt.service.UserService" scope="prototype"> ,则每便调用getBean都会获得新的实例,结果就为false了;

  singleton 最常用;prototype 视意况而定。

  前面包车型地铁多少个布局一般在SpringMVC框架中才会涉及到,这里不做探寻。

代码链接: 密码: ishj

jar包链接: 密码: fejx

功能域(bean 的生命周期),scopebean 暗中认可是 singleton ,单例情势,如下代码: 1 @Test 2 public void testAddUser() throws Exception { 3 ApplicationContext...

图片 2

 

Spring框架第二篇之Bean的装配,spring第二篇bean

Spring 的Bean暗中同意的是单例的.

暗中同意是 singleton ,单例情势,如下代码:

Spring Bean的作用域

一、暗中同意装配格局

代码通过getBean();格局从容器中得到内定的Bean实例,容器首先会调用Bean类的无参构造器,创立空值的实例对象。

举例:

率先小编在applicationContext.xml配置文件中布局了三个bean:

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

    <!-- 注册Service 这里相当于容器做了SomeServiceImpl myService = new SomeServiceImpl(); -->
    <bean id="myService" class="com.ietree.spring.basic.ioc.SomeServiceImpl"/>

</beans>

成立SomeServiceImpl对象,但供给留神的是此类的只持有带参构造函器,未有无参构造器:

package com.ietree.spring.basic.ioc;

/**
 * 实现类
 * 
 * @author Root
 */
public class SomeServiceImpl implements ISomeService {

    private int a;

    // 这里注释掉了无参构造函数,希望容器通过带参构造函数创建对象
//    public SomeServiceImpl() {
//        System.out.println("执行无参构造器,创建SomeServiceImpl对象");
//    }

    public SomeServiceImpl(int a) {
        this.a = a;
    }

    @Override
    public void doSomeThing() {
        System.out.println("执行doSomeThing()方法...");
    }

}

测试:

@Test
public void testConstructor() {

    // 创建容器对象,加载Spring配置文件
    // ClassPathXmlApplicationContext会从类路径下查找配置文件
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

    ISomeService service = (ISomeService) ac.getBean("myService");
    service.doSomeThing();
}

那会儿先后会报以下的一无所长:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.ietree.spring.basic.ioc.SomeServiceImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.ietree.spring.basic.ioc.SomeServiceImpl.<init>()
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.ietree.spring.basic.test.MyTest.testConstrutor(MyTest.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.ietree.spring.basic.ioc.SomeServiceImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.ietree.spring.basic.ioc.SomeServiceImpl.<init>()
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:85)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147)
    ... 36 more
Caused by: java.lang.NoSuchMethodException: com.ietree.spring.basic.ioc.SomeServiceImpl.<init>()
    at java.lang.Class.getConstructor0(Unknown Source)
    at java.lang.Class.getDeclaredConstructor(Unknown Source)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80)
    ... 37 more

深入分析:这里的不当报的很显然,未有察觉私下认可的构造器。

修改:为此类加上无参构造器:

package com.ietree.spring.basic.ioc;

/**
 * 实现类
 * 
 * @author Root
 */
public class SomeServiceImpl implements ISomeService {

    private int a;

    public SomeServiceImpl() {
        System.out.println("执行无参构造器,创建SomeServiceImpl对象");
    }

    public SomeServiceImpl(int a) {
        this.a = a;
    }

    @Override
    public void doSomeThing() {
        System.out.println("执行doSomeThing()方法...");
    }

}

那时候,再一次运营测量检验用例,会意识运营成功。

敲定:Spring容器实际上是运用了类的反射机制,会首先调用Bean类的无参构造器创造实例对象。

固然不想单例需求如下配置:

 1     @Test
 2     public void testAddUser() throws Exception {
 3         ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");//初始化ApplicationContext对象,加载配置文件
 4         
 5         UserService service = (UserService)ctx.getBean("userService");//从容器中取
 6         UserService service2 = (UserService)ctx.getBean("userService");//从容器中取
 7         
 8         System.out.println(service == service2);//true
 9         
10         User u = new User();
11         u.setUsername("zhangsan");
12         u.setPassword("zhangsan");
13         service.addUser(u);//容器中已经配置了UserDAOImpl了,并把DAOImpl注入到service之中,所以service直接就可以保存了
14     }

图片 3

二、动态工厂Bean

 创建SomeServiceImpl类:

package com.ietree.spring.basic.ioc;

/**
 * 实现类
 * 
 * @author Root
 */
public class SomeServiceImpl implements ISomeService {

    public SomeServiceImpl() {
        System.out.println("执行无参构造器,创建SomeServiceImpl对象");
    }

    @Override
    public void doSomeThing() {
        System.out.println("执行doSomeThing()方法...");
    }

}

创造工厂类ServiceFactory:

package com.ietree.spring.basic.ioc;

/**
 * 工厂类
 * 
 * @author Root
 */
public class ServiceFactory {

    public ISomeService getSomeService() {
        return new SomeServiceImpl();
    }

}

选取动态工厂格局获得Bean对象,配置如下:

<?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="factory" class="com.ietree.spring.basic.ioc.ServiceFactory"/>

    <!-- 注册Service:动态工厂Bean -->
    <bean id="myService" factory-bean="factory" factory-method="getSomeService"/>

</beans>

在此间并不曾注册SomeServiceImpl类,而是经过ServiceFactory工厂的getSomeService方法获得的。

测试:

@Test
public void testFactory1() {

    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    ISomeService service = (ISomeService) ac.getBean("myService");
    service.doSomeThing();
}

运营成功。

<bean id="user" class="..." scope="singleton"/>

  获取的 service 和 service2 都以二个指标,结果为true。

.singleton  [单例] eg:<bean id="personService" class="com.yinger.service.impl.PersonServiceBean" scope="singleton"></bean>

三、静态工厂Bean

 静态工厂和动态工厂区别的是,静态工厂中动用的是静态方法制造对象,如:

package com.ietree.spring.basic.ioc;

/**
 * 工厂类
 * 
 * @author Root
 */
public class ServiceFactory {

    // 使用静态方法创建对象
    public static ISomeService getSomeService() {
        return new SomeServiceImpl();
    }

}

对应的配置文件修改如下:

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

    <!-- 注册Service:静态工厂Bean -->
    <bean id="myService" class="com.ietree.spring.basic.ioc.ServiceFactory" factory-method="getSomeService"/>

</beans>

测试:

@Test
public void testFactory1() {

    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    ISomeService service = (ISomeService) ac.getBean("myService");
    service.doSomeThing();
}

职业有成成立SomeServiceImpl对象。

scope="singleton"正是计划那一个bean是单例的,暗许不写正是singleton。

  假设将 scope 设置为 prototype: 1 <bean id="userService" class="com.bjsxt.service.UserService" scope="prototype"> ,则每回调用getBean都会赢得新的实例,结果就为false了;

在各样Spring IoC容器中三个bean定义独有八个对象实例。

四、容器中的Bean的成效域

 Bean的效能域(scope)分为八种,分别是singleton、prototype、request、session。

scope:
  singleton(暗许):单例方式,其目的的开创机遇是在Spring容器早先化时创设,是私下认可值
  prototype:原型形式,其目的的创造时机不是在Spring容器发轫化时创立,而是在代码中真的访谈时才创制,每一趟使用getBean方法得到的同二个<bean/>的实例都以二个新的实例
  request:对于每一次HTTP诉求,都将会时有产生三个例外的Bean实例
  session:对于每种差异的HTTP session,都将会生出一个不如的Bean实例

验证:

首先配置作用域为singleton:

<bean id="myService" class="com.ietree.spring.basic.ioc.SomeServiceImpl" scope="singleton"/>

测试:

@Test
public void test05() {

    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

    ISomeService service1 = (ISomeService) ac.getBean("myService");
    ISomeService service2 = (ISomeService) ac.getBean("myService");
    System.out.println("service1 = service2吗?"   (service1 == service2));
}

次第输出:

调用无参构造器
service1 = service2吗?true

敲定:当功用域为singleton单例格局时,只会成立七个对象实例,並且对象是在Spring容器初叶化时创制。

一致,当配置为prototype原型情势时:

<bean id="myService" class="com.ietree.spring.basic.ioc.SomeServiceImpl" scope="prototype"/>

次第输出:

调用无参构造器
调用无参构造器
service1 = service2吗?false

敲定:构造器被调用了两遍,说明创造的service1和service2不是同二个对象,况且对象是在被采纳到时才成立的。

scope 换到 prototype 就不是单例的了。

  singleton 最常用;prototype 视意况而定。

请小心Spring的singleton bean概念与“多人帮”(GoF)格局一书中定义的Singleton方式是一心两样的。

五、Bean后Computer

 

 

本文由1010cc时时彩标准版发布于三分时时彩1010CC,转载请注明出处:的生命周期,Bean的作用域

关键词:

上一篇:【1010cc时时彩标准版】设计格局详解,设计方式

下一篇:没有了