spring 学习2-Spring Configuration in detail

简介:

1.Bean Life-Cycle Management

 

Xml代码   收藏代码
  1. <bean id="simpleBean1"   
  2. class="com.apress.prospring3.ch5.lifecycle.SimpleBean"   
  3. init-method="init" />   

 

Xml代码   收藏代码
  1. <bean id="destructiveBean"   
  2. class="com.apress.prospring3.ch5.lifecycle.DestructiveBean"   
  3. destroy-method="destroy"/>  

 

Java代码   收藏代码
  1. public class SimpleBeanWithInterface implements InitializingBean{   
  2. private static final String DEFAULT_NAME = "Luke Skywalker";   
  3. private String name = null;   
  4. private int age = Integer.MIN_VALUE;   
  5. public void setName(String name) {   
  6. this.name = name;   
  7. }   
  8. public void setAge(int age) {   
  9. this.age = age;   
  10. }   
  11. public void myInit() {   
  12. System.out.println("My Init");   
  13. }   
  14. public void afterPropertiesSet() throws Exception {   
  15. System.out.println("Initializing bean");   
  16. if (name == null) {   
  17. System.out.println("Using default name");   
  18. name = DEFAULT_NAME;   
  19. }   

 

Java代码   收藏代码
  1. public class DestructiveBeanWithInterface implements InitializingBean,   
  2. DisposableBean{   
  3. private InputStream is = null;   
  4. public String filePath = null;   
  5. public void afterPropertiesSet() throws Exception {   
  6. System.out.println("Initializing Bean");   
  7. if (filePath == null) {   
  8. throw new IllegalArgumentException(   
  9. "You must specify the filePath property of " + DestructiveBean.class);   
  10. }   
  11. is = new FileInputStream(filePath);   
  12. }   
  13. public void destroy() {   
  14. System.out.println("Destroying Bean");   
  15. if (is != null) {   
  16. try {    
  17. is.close();   
  18. is = null;   
  19. catch (IOException ex) {   
  20. System.err.println("WARN: An IOException occured"   
  21. " trying to close the InputStream");   
  22. }   
  23. }   
  24. }   
  25. public void setFilePath(String filePath) {   
  26. this.filePath = filePath;   
  27. }  

 

Java代码   收藏代码
  1. public class SimpleBeanWithJSR250 {   
  2. // Codes omitted   
  3. @PostConstruct   
  4. public void init() throws Exception {   
  5. // Rest of codes omitted   
  6. }   
  7. }   

 

Java代码   收藏代码
  1. public class DestructiveBeanWithJSR250 {   
  2. private InputStream is = null;   
  3. public String filePath = null;   
  4. @PostConstruct   
  5. public void afterPropertiesSet() throws Exception {   
  6. System.out.println("Initializing Bean");   
  7. if (filePath == null) {   
  8. throw new IllegalArgumentException(   
  9. "You must specify the filePath property of " + DestructiveBean.class);   
  10. }   
  11. is = new FileInputStream(filePath);   
  12. }   
  13. @PreDestroy   
  14. public void destroy() {   
  15. System.out.println("Destroying Bean");   
  16. if (is != null) {   
  17. try {   
  18. is.close();   
  19. is = null;   
  20. catch (IOException ex) {   
  21. System.err.println("WARN: An IOException occured"   
  22. " trying to close the InputStream");   
  23. }   
  24. }   
  25. }   
  26. public void setFilePath(String filePath) {   
  27. this.filePath = filePath;   
  28. }   

 2.Making Your Beans “spring Aware”

 

 

Java代码   收藏代码
  1. public class ShutdownHookBean implements ApplicationContextAware {   
  2. private ApplicationContext ctx;   
  3. public void setApplicationContext(ApplicationContext ctx)   
  4. throws BeansException {   
  5. if (ctx instanceof GenericApplicationContext) {   
  6. ((GenericApplicationContext) ctx).registerShutdownHook();   
  7. }   
  8. }   
  9. }   

 

Xml代码   收藏代码
  1. <bean id="destructiveBean"   
  2. class="com.apress.prospring3.ch5.lifecycle.DestructiveBeanWithInterface">   
  3. <property name="filePath">   
  4. <value>d:/temp/test.txt</value>   
  5. </property>   
  6. </bean>   
  7. <bean id="shutdownHook"   
  8. class="com.apress.prospring3.ch5.interaction.ShutdownHookBean"/>   

 3.Using ApplicationContext and MessageSource 

 

 

Java代码   收藏代码
  1. public static void main(String[] args) {   
  2. GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();   
  3. ctx.load("classpath:appContext/messageSource.xml");   
  4. ctx.refresh();   
  5. Locale english = Locale.ENGLISH;   
  6. Locale czech = new Locale("cs""CZ");   
  7. System.out.println(ctx.getMessage("msg"null, english));   
  8. System.out.println(ctx.getMessage("msg"null, czech));   
  9. System.out.println(ctx.getMessage("nameMsg"new Object[] { "Clarence",   
  10. "Ho" }, english));   
  11. }   
Xml代码   收藏代码
  1. <bean id="messageSource"   
  2. class="org.springframework.context.support.ResourceBundleMessageSource">   
  3. <property name="basenames">   
  4. <list>   
  5. <value>buttons</value>   
  6. <value>labels</value>   
  7. </list>   
  8. </property>   
  9. </bean>   
  10.    

 

 4.Using Application Events 

 

 

Java代码   收藏代码
  1. public class MessageEvent extends ApplicationEvent {   
  2. private String msg;   
  3. public MessageEvent(Object source, String msg) {   
  4. super(source);   
  5. this.msg = msg;   
  6. }   
  7. public String getMessage() {   
  8. return msg;   
  9. }   
  10. }   

 

Java代码   收藏代码
  1. public class MessageEventListener implements ApplicationListener<MessageEvent> {   
  2. public void onApplicationEvent(MessageEvent event) {   
  3. MessageEvent msgEvt = (MessageEvent) event;   
  4. System.out.println("Received: " + msgEvt.getMessage());   
  5. }   
  6. }   

 

Java代码   收藏代码
  1. public class Publisher implements ApplicationContextAware {   
  2. private ApplicationContext ctx;   
  3. public static void main(String[] args) {   
  4. ApplicationContext ctx = new ClassPathXmlApplicationContext(   
  5. "classpath:events/events.xml");   
  6. Publisher pub = (Publisher) ctx.getBean("publisher");   
  7. pub.publish("Hello World!");   
  8. pub.publish("The quick brown fox jumped over the lazy dog");   
  9. }   
  10. public void setApplicationContext(ApplicationContext applicationContext)   
  11. throws BeansException {   
  12. this.ctx = applicationContext;   
  13. }   
  14. public void publish(String message) {   
  15. ctx.publishEvent(new MessageEvent(this, message));   
  16. }   
  17. }  

 

Xml代码   收藏代码
  1. <bean id="publisher" class="com.apress.prospring3.ch5.event.Publisher"/>   
  2. <bean id="messageEventListener"   
  3. class="com.apress.prospring3.ch5.event.MessageEventListener"/>  

 5.Accessing Resources

Java代码   收藏代码
  1. public static void main(String[] args) throws Exception{   
  2. ApplicationContext ctx = new ClassPathXmlApplicationContext(   
  3. "classpath:events/events.xml");   
  4. Resource res1 = ctx.getResource("file:///d:/temp/test.txt");   
  5. displayInfo(res1);   
  6. Resource res2 = ctx.getResource("classpath:test.txt");   
  7. displayInfo(res2);   
  8. Resource res3 = ctx.getResource("http://www.google.co.uk");   
  9. displayInfo(res3);   
  10. }   
  11. private static void displayInfo(Resource res) throws Exception{   
  12. System.out.println(res.getClass());   
  13. System.out.println(res.getURL().getContent());   
  14. System.out.println("");   
  15. //getFile(), getInputStream(), or getURL()  
  16. }  
  17. <strong>6. Java Configuration  
  18. </strong>  
Java代码   收藏代码
  1. @Configuration   
  2. public class AppConfig {   
  3. // XML:   
  4. // <bean id="messageProvider"   
  5. class="com.apress.prospring3.ch5.javaconfig.ConfigurableMessageProvider"/>   
  6. @Bean   
  7. public MessageProvider messageProvider() {   
  8. return new ConfigurableMessageProvider();   
  9. }   
  10. // XML:   
  11. // <bean id="messageRenderer"   
  12. class="com.apress.prospring3.ch5.javaconfig.StandardOutMessageRenderer"   
  13. // p:messageProvider-ref="messageProvider"/>   
  14. @Bean   
  15. public MessageRenderer messageRenderer() {   
  16. MessageRenderer renderer = new StandardOutMessageRenderer();   
  17. // Setter injection   
  18. renderer.setMessageProvider(messageProvider());   
  19. return renderer;   
  20. }   
Java代码   收藏代码
  1. <strong>   
  2. </strong>  

 

Java代码   收藏代码
  1. @Configuration   
  2. @Import(OtherConfig.class)   
  3. // XML: <import resource="classpath:events/events.xml")   
  4. @ImportResource(value="classpath:events/events.xml")   
  5. // XML: <context:property-placeholder location="classpath:message.properties"/>   
  6. @PropertySource(value="classpath:message.properties")   
  7. // XML: <context:component-scan base-package="com.apress.prospring3.ch5.context"/>   
  8. @ComponentScan(basePackages={"com.apress.prospring3.ch5.context"})   
  9. @EnableTransactionManagement public class AppConfig {   
  10. @Autowired   
  11. Environment env;   
  12. // XML:   
  13. // <bean id="messageProvider"   
  14. class="com.apress.prospring3.ch5.javaconfig.ConfigurableMessageProvider"/>   
  15. @Bean   
  16. @Lazy(value=true//XML <bean .... lazy-init="true"/>   
  17. public MessageProvider messageProvider() {   
  18. // Constructor injection   
  19. return new ConfigurableMessageProvider(env.getProperty("message"));   
  20. }   
  21. // XML:   
  22. // <bean id="messageRenderer"   
  23. class="com.apress.prospring3.ch5.javaconfig.StandardOutMessageRenderer"   
  24. // p:messageProvider-ref="messageProvider"/>   
  25. @Bean(name="messageRenderer")   
  26. @Scope(value="prototype"// XML: <bean ... scope="prototype"/>   
  27. @DependsOn(value="messageProvider"// XML: <bean ... depends-on="messageProvider"/>   
  28. public MessageRenderer messageRenderer() {   
  29. MessageRenderer renderer = new StandardOutMessageRenderer();   
  30. // Setter injection   
  31. renderer.setMessageProvider(messageProvider());   
  32. return renderer;   
  33. }   
  34. }   

 7.ConfigurableEnvironment env = ctx.getEnvironment(); 

MutablePropertySources propertySources = env.getPropertySources(); 

8.JSR-330

Java代码   收藏代码
  1. @Named("messageRenderer")   
  2. @Singleton   
  3. public class StandardOutMessageRenderer implements MessageRenderer {   
  4. @Inject   
  5. @Named("messageProvider")   
  6. private MessageProvider messageProvider = null;   
  7. public void render() {   
  8. if (messageProvider == null) {   
  9. throw new RuntimeException(   
  10. "You must set the property messageProvider of class:"   
  11. + StandardOutMessageRenderer.class.getName());   
  12. }   
  13. System.out.println(messageProvider.getMessage());   
  14. }   
  15. public void setMessageProvider(MessageProvider provider) {   
  16. this.messageProvider = provider;   
  17. }   
  18. public MessageProvider getMessageProvider() {   
  19. return this.messageProvider;   
  20. }   
  21. }   
目录
相关文章
|
22天前
|
搜索推荐 JavaScript Java
基于springboot的儿童家长教育能力提升学习系统
本系统聚焦儿童家长教育能力提升,针对家庭教育中理念混乱、时间不足、个性化服务缺失等问题,构建科学、系统、个性化的在线学习平台。融合Spring Boot、Vue等先进技术,整合优质教育资源,提供高效便捷的学习路径,助力家长掌握科学育儿方法,促进儿童全面健康发展,推动家庭和谐与社会进步。
|
8月前
|
监控 Java 应用服务中间件
微服务——SpringBoot使用归纳——为什么学习Spring Boot
本文主要探讨为什么学习Spring Boot。从Spring官方定位来看,Spring Boot旨在快速启动和运行项目,简化配置与编码。其优点包括:1) 良好的基因,继承了Spring框架的优点;2) 简化编码,通过starter依赖减少手动配置;3) 简化配置,采用Java Config方式替代繁琐的XML配置;4) 简化部署,内嵌Tomcat支持一键式启动;5) 简化监控,提供运行期性能参数获取功能。此外,从未来发展趋势看,微服务架构逐渐成为主流,而Spring Boot作为官方推荐技术,与Spring Cloud配合使用,将成为未来发展的重要方向。
246 0
微服务——SpringBoot使用归纳——为什么学习Spring Boot
|
5月前
|
安全 Java 数据库
Spring Boot 框架深入学习示例教程详解
本教程深入讲解Spring Boot框架,先介绍其基础概念与优势,如自动配置、独立运行等。通过搭建项目、配置数据库等步骤展示技术方案,并结合RESTful API开发实例帮助学习。内容涵盖环境搭建、核心组件应用(Spring MVC、Spring Data JPA、Spring Security)及示例项目——在线书店系统,助你掌握Spring Boot开发全流程。代码资源可从[链接](https://pan.quark.cn/s/14fcf913bae6)获取。
589 3
|
7月前
|
Java Spring
Spring框架的学习与应用
总的来说,Spring框架是Java开发中的一把强大的工具。通过理解其核心概念,通过实践来学习和掌握,你可以充分利用Spring框架的强大功能,提高你的开发效率和代码质量。
168 20
|
Java Maven Spring
springboot学习一:idea社区版本创建springboot项目的三种方式(第三种为主)
这篇文章介绍了在IntelliJ IDEA社区版中创建Spring Boot项目的三种方法,特别强调了第三种方法的详细步骤。
10191 0
springboot学习一:idea社区版本创建springboot项目的三种方式(第三种为主)
|
12月前
|
前端开发 Java 开发者
Spring生态学习路径与源码深度探讨
【11月更文挑战第13天】Spring框架作为Java企业级开发中的核心框架,其丰富的生态系统和强大的功能吸引了无数开发者的关注。学习Spring生态不仅仅是掌握Spring Framework本身,更需要深入理解其周边组件和工具,以及源码的底层实现逻辑。本文将从Spring生态的学习路径入手,详细探讨如何系统地学习Spring,并深入解析各个重点的底层实现逻辑。
247 9
|
数据采集 监控 Java
SpringBoot日志全方位超详细手把手教程,零基础可学习 日志如何配置及SLF4J的使用......
本文是关于SpringBoot日志的详细教程,涵盖日志的定义、用途、SLF4J框架的使用、日志级别、持久化、文件分割及格式配置等内容。
779 2
SpringBoot日志全方位超详细手把手教程,零基础可学习 日志如何配置及SLF4J的使用......
|
存储 开发框架 Java
什么是Spring?什么是IOC?什么是DI?IOC和DI的关系? —— 零基础可无压力学习,带源码
文章详细介绍了Spring、IOC、DI的概念和关系,解释了控制反转(IOC)和依赖注入(DI)的原理,并提供了IOC的代码示例,阐述了Spring框架作为IOC容器的应用。
802 1
什么是Spring?什么是IOC?什么是DI?IOC和DI的关系? —— 零基础可无压力学习,带源码
|
前端开发 Java 数据库
SpringBoot学习
【10月更文挑战第7天】Spring学习
158 9
|
XML Java 数据格式
Spring学习
【10月更文挑战第6天】Spring学习
103 1

热门文章

最新文章

下一篇
开通oss服务