Spring中Bean的作用域差别

我觉得servlet和spring交叉起来,理解得快。

Bean的作用域中,prototype和singleton作用域效果不一样,前者每次都会有新的实例,而后者始终一个实例 。

所以,java.util.date在prototype时,会输出不同的时间,而singleton时只会输出同一个时间。

config.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"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:aop="http://www.springframework.org/schema/aop"
             xmlns:tx="http://www.springframework.org/schema/tx"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
                     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                     http://www.springframework.org/schema/context
                     http://www.springframework.org/schema/context/spring-context-3.0.xsd
                     http://www.springframework.org/schema/aop
                     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                     http://www.springframework.org/schema/tx
                     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    <bean id="date" class="java.util.Date" scope="singleton" />
    
</beans>

 

DateSpringTest.java:

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

public class DateSpringTest {
    public static void main(String[] args) throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
        System.out.println("Get date: " + context.getBean("date"));
        Thread.sleep(2000);
        System.out.println("Get date: " + context.getBean("date"));
        Thread.sleep(2000);
        System.out.println("Get date: " + context.getBean("date"));
    }

}

Spring中Bean的作用域差别_第1张图片

 

你可能感兴趣的:(Spring中Bean的作用域差别)