3. Spring4.x BeanのScope
1699 ワード
BeanのScopeの簡単な例
@Scopeで次のパラメータ値を指定します.新しいScope Singletonクラス 新しいScopeをPrototypeとするクラス 構成クラス Mainテスト
@Scopeで次のパラメータ値を指定します.
Singleton ( )
Prototype
Request web request
Session web session
GlobalSession portal ( ...)
package com.xiaohan.scope;
import org.springframework.stereotype.Service;
@Service
//
// @Scope("singleton")
public class SingletonService {
}
package com.xiaohan.scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope("prototype")
public class PrototypeService {
}
package com.xiaohan.scope;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.xiaohan.scope")
public class ScopeConfig {
}
package com.xiaohan.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// Bean Scope
public class Main {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(ScopeConfig.class);
SingletonService s1 = ac.getBean(SingletonService.class);
SingletonService s2 = ac.getBean(SingletonService.class);
System.err.println(s1.equals(s2)); //true
PrototypeService p1 = ac.getBean(PrototypeService.class);
PrototypeService p2 = ac.getBean(PrototypeService.class);
System.err.println(p1.equals(p2)); //false
}
}