本文共 2649 字,大约阅读时间需要 8 分钟。
Spring中有5种bean的范围: |
5 types of bean scopes supported :
P.S * means only valid in the context of a web-aware Spring ApplicationContext
我们看个关于singleton and prototype.的例子:
1 2 3 4 5 6 7 8 9 10 11 12 | public class CustomerService { String message; public String getMessage() { return message; } public void setMessage(String message) { this .message = message; } } |
1 2 3 4 5 6 7 8 9 | <beans xmlns= "" xmlns:xsi= "" xsi:schemaLocation="http: //www.springframework.org/schema/beans http: //www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id= "customerService" class = "com.mkyong.customer.services.CustomerService" /> </beans> |
运行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class App { public static void main( String[] args ) { ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "Spring-Customer.xml" }); CustomerService custA = (CustomerService)context.getBean( "customerService" ); custA.setMessage( "Message by custA" ); System.out.println( "Message : " + custA.getMessage()); //retrieve it again CustomerService custB = (CustomerService)context.getBean( "customerService" ); System.out.println( "Message : " + custB.getMessage()); } } |
输出为:
Message : Message by custAMessage : Message by custA
1 2 3 4 5 6 7 8 9 | < beans xmlns="" xmlns:xsi="" xsi:schemaLocation=" "> < bean id="customerService" class="com.mkyong.customer.services.CustomerService" scope="prototype"/> </ beans > |
运行输出为:
Message : Message by custAMessage : null 也可以使用注解来做这些事情:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package com.mkyong.customer.services; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; @Service @Scope ( "prototype" ) public class CustomerService { String message; public String getMessage() { return message; } public void setMessage(String message) { this .message = message; } } |
1 2 3 4 5 6 7 8 9 10 11 | <beans xmlns= "" xmlns:xsi= "" xmlns:context= "" xsi:schemaLocation="http: //www.springframework.org/schema/beans http: //www.springframework.org/schema/beans/spring-beans-2.5.xsd http: //www.springframework.org/schema/context http: //www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base- package = "com.mkyong.customer" /> </beans> |
转载地址:http://vbbbm.baihongyu.com/