Bean的作用域

在 XML 配置中注册的 Bean,或者用 Java 配置注册的 Bean,如果我多次获取,获取到的对象是否是同一个?

public class Main {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user = ctx.getBean("user", User.class);
        User user2 = ctx.getBean("user", User.class);
        System.out.println(user==user2);
    }
}

如上,从 Spring 容器中多次获取同一个 Bean,默认情况下,获取到的实际上是同一个实例。当然我们可以自己手动配置。

<bean class="org.javaboy.User" id="user" scope="prototype" />

通过在 XML 节点中,设置 scope 属性,我们可以调整默认的实例个数。scope 的值为 singleton(默认),表示这个 Bean 在 Spring 容器中,是以单例的形式存在,如果 scope 的值为 prototype,表示这个 Bean 在 Spring 容器中不是单例,多次获取将拿到多个不同的实例。

除了 singleton 和 prototype 之外,还有两个取值,request 和 session。这两个取值在 web 环境下有效。这是在 XML 中的配置,我们也可以在 Java 中配置。

@Configuration
public class JavaConfig {
    @Bean
    @Scope("prototype")
    SayHello sayHello() {
        return new SayHello();
    }
}

在 Java 代码中,我们可以通过 @Scope 注解指定 Bean 的作用域。

当然,在自动扫描配置中,也可以指定 Bean 的作用域。

@Repository
@Scope("prototype")
public class UserDao {
    public String hello() {
        return "userdao";
    }
}
posted @ 2020-08-03 19:01  柒丶月  阅读(108)  评论(0编辑  收藏  举报