java Bean范围(单例,会话,请求,原型)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Bean范围(单例,会话,请求,原型)相关的知识,希望对你有一定的参考价值。
<!-- using prototype scope in xml -->
<!-- everytime the object will be different -->
<?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 name="myCustomerRepository"
class="com.pluralsight.repository.HibernateCustomerRepositoryImpl" />
<bean name="customerService" class="com.pluralsight.service.CustomerServiceImpl" autowire="byName" scope="prototype">
<!-- <property name="customerRepository" ref="myCustomerRepository" /> -->
<!-- <constructor-arg index="0" ref="myCustomerRepository"></constructor-arg> -->
</bean>
</beans>
// Can use @Scope("singleton") or using the configuratbleBeanFactory
package com.pluralsight.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.pluralsight.model.Customer;
import com.pluralsight.repository.CustomerRepository;
@Service("customerService")
@Scope("singleton")
//@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class CustomerServiceImpl implements CustomerService {
private CustomerRepository customerRepository;
/* (non-Javadoc)
* @see com.pluralsight.service.CustomerService#findAll()
*/
public CustomerServiceImpl(){
}
public CustomerServiceImpl(CustomerRepository repo){
System.out.println("Constructor injection");
this.customerRepository = repo;
}
@Override
public List<Customer> findAll(){
return customerRepository.findAll();
}
@Autowired
public void setCustomerRepository(CustomerRepository customerRepository) {
System.out.println("Setter injection");
this.customerRepository = customerRepository;
}
}
以上是关于java Bean范围(单例,会话,请求,原型)的主要内容,如果未能解决你的问题,请参考以下文章
spring:使用会话和请求作用域
Spring会话范围的bean作为原型bean中的依赖项?
在Spring上下文中的原型bean中的单例bean
Bean作用域
Spring实战Bean 的作用域
Spring框架参考手册(4.2.6版本)翻译——第三部分 核心技术 6.5.2 原型(prototype)作用域