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. }   
目录
相关文章
|
2月前
|
JavaScript Java 测试技术
基于springboot+vue.js+uniapp的公考学习平台附带文章源码部署视频讲解等
基于springboot+vue.js+uniapp的公考学习平台附带文章源码部署视频讲解等
40 5
|
18天前
|
小程序 前端开发 Java
SpringBoot+uniapp+uview打造H5+小程序+APP入门学习的聊天小项目
JavaDog Chat v1.0.0 是一款基于 SpringBoot、MybatisPlus 和 uniapp 的简易聊天软件,兼容 H5、小程序和 APP,提供丰富的注释和简洁代码,适合初学者。主要功能包括登录注册、消息发送、好友管理及群组交流。
41 0
SpringBoot+uniapp+uview打造H5+小程序+APP入门学习的聊天小项目
|
27天前
|
缓存 前端开发 JavaScript
前后端分离 SpringBoot+Vue商城买卖系统通杀版本。大家可以参考学习一下
这篇文章介绍了一个使用SpringBoot+Vue开发的前后端分离商城系统,包括技术架构、开发环境、实现的功能以及项目截图,并展示了普通用户和商家端的功能界面。
前后端分离 SpringBoot+Vue商城买卖系统通杀版本。大家可以参考学习一下
|
2月前
|
Java 数据格式 微服务
2024最新首发,全网最全 Spring Boot 学习宝典(附思维导图)
📚 《滚雪球学Spring Boot》是由CSDN博主bug菌创作的全面Spring Boot教程。作者是全栈开发专家,在多个技术社区如CSDN、掘金、InfoQ、51CTO等担任博客专家,并拥有超过20万的全网粉丝。该教程分为入门篇和进阶篇,每篇包含详细的教学步骤,涵盖Spring Boot的基础和高级主题。
170 4
2024最新首发,全网最全 Spring Boot 学习宝典(附思维导图)
|
2月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue+uniapp的在线学习过程管理系统的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue+uniapp的在线学习过程管理系统的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue+uniapp的在线学习过程管理系统的详细设计和实现(源码+lw+部署文档+讲解等)
|
2月前
|
安全 Java 数据库
三更草堂 Spring Security学习总结(思路整理)
Spring Security学习总结(思路整理)
|
26天前
|
设计模式 Java 程序员
学习 Spring 源码的意义是什么呢?
研究Spring源码能深化框架理解,提升代码分析与设计能力,助您掌握设计模式及最佳实践,增强解决问题的效率,促进职业生涯发展,并激发技术热情。选择稳定版本,从核心模块开始,结合实际项目并参与社区,让学习之旅既充实又具乐趣。
|
2月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue+uniapp的大学生国学自主学习平台的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue+uniapp的大学生国学自主学习平台的详细设计和实现(源码+lw+部署文档+讲解等)
|
2月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue+uniapp的诗词学习系统的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue+uniapp的诗词学习系统的详细设计和实现(源码+lw+部署文档+讲解等)
|
2月前
|
JavaScript Java 测试技术
基于springboot+vue.js+uniapp的学生网课学习效果评价附带文章源码部署视频讲解等
基于springboot+vue.js+uniapp的学生网课学习效果评价附带文章源码部署视频讲解等
59 2