`
wiselyman
  • 浏览: 2094423 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
博客专栏
Group-logo
点睛Spring4.1
浏览量:82377
74ae1471-94c5-3ae2-b227-779326b57435
点睛Spring MVC4...
浏览量:130819
社区版块
存档分类
最新评论

spring 学习2-Spring Configuration in detail

 
阅读更多

1.Bean Life-Cycle Management

 

<bean id="simpleBean1" 
class="com.apress.prospring3.ch5.lifecycle.SimpleBean" 
init-method="init" /> 

 

<bean id="destructiveBean" 
class="com.apress.prospring3.ch5.lifecycle.DestructiveBean" 
destroy-method="destroy"/>

 

public class SimpleBeanWithInterface implements InitializingBean{ 
private static final String DEFAULT_NAME = "Luke Skywalker"; 
private String name = null; 
private int age = Integer.MIN_VALUE; 
public void setName(String name) { 
this.name = name; 
} 
public void setAge(int age) { 
this.age = age; 
} 
public void myInit() { 
System.out.println("My Init"); 
} 
public void afterPropertiesSet() throws Exception { 
System.out.println("Initializing bean"); 
if (name == null) { 
System.out.println("Using default name"); 
name = DEFAULT_NAME; 
} 

 

public class DestructiveBeanWithInterface implements InitializingBean, 
DisposableBean{ 
private InputStream is = null; 
public String filePath = null; 
public void afterPropertiesSet() throws Exception { 
System.out.println("Initializing Bean"); 
if (filePath == null) { 
throw new IllegalArgumentException( 
"You must specify the filePath property of " + DestructiveBean.class); 
} 
is = new FileInputStream(filePath); 
} 
public void destroy() { 
System.out.println("Destroying Bean"); 
if (is != null) { 
try {  
is.close(); 
is = null; 
} catch (IOException ex) { 
System.err.println("WARN: An IOException occured" 
+ " trying to close the InputStream"); 
} 
} 
} 
public void setFilePath(String filePath) { 
this.filePath = filePath; 
}

 

public class SimpleBeanWithJSR250 { 
// Codes omitted 
@PostConstruct 
public void init() throws Exception { 
// Rest of codes omitted 
} 
} 

 

public class DestructiveBeanWithJSR250 { 
private InputStream is = null; 
public String filePath = null; 
@PostConstruct 
public void afterPropertiesSet() throws Exception { 
System.out.println("Initializing Bean"); 
if (filePath == null) { 
throw new IllegalArgumentException( 
"You must specify the filePath property of " + DestructiveBean.class); 
} 
is = new FileInputStream(filePath); 
} 
@PreDestroy 
public void destroy() { 
System.out.println("Destroying Bean"); 
if (is != null) { 
try { 
is.close(); 
is = null; 
} catch (IOException ex) { 
System.err.println("WARN: An IOException occured" 
+ " trying to close the InputStream"); 
} 
} 
} 
public void setFilePath(String filePath) { 
this.filePath = filePath; 
} 

 2.Making Your Beans “Spring Aware”

 

 

public class ShutdownHookBean implements ApplicationContextAware { 
private ApplicationContext ctx; 
public void setApplicationContext(ApplicationContext ctx) 
throws BeansException { 
if (ctx instanceof GenericApplicationContext) { 
((GenericApplicationContext) ctx).registerShutdownHook(); 
} 
} 
} 

 

<bean id="destructiveBean" 
class="com.apress.prospring3.ch5.lifecycle.DestructiveBeanWithInterface"> 
<property name="filePath"> 
<value>d:/temp/test.txt</value> 
</property> 
</bean> 
<bean id="shutdownHook" 
class="com.apress.prospring3.ch5.interaction.ShutdownHookBean"/> 

 3.Using ApplicationContext and MessageSource 

 

 

public static void main(String[] args) { 
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); 
ctx.load("classpath:appContext/messageSource.xml"); 
ctx.refresh(); 
Locale english = Locale.ENGLISH; 
Locale czech = new Locale("cs", "CZ"); 
System.out.println(ctx.getMessage("msg", null, english)); 
System.out.println(ctx.getMessage("msg", null, czech)); 
System.out.println(ctx.getMessage("nameMsg", new Object[] { "Clarence", 
"Ho" }, english)); 
} 

<bean id="messageSource" 
class="org.springframework.context.support.ResourceBundleMessageSource"> 
<property name="basenames"> 
<list> 
<value>buttons</value> 
<value>labels</value> 
</list> 
</property> 
</bean> 
 

 

 4.Using Application Events 

 

 

public class MessageEvent extends ApplicationEvent { 
private String msg; 
public MessageEvent(Object source, String msg) { 
super(source); 
this.msg = msg; 
} 
public String getMessage() { 
return msg; 
} 
} 

 

public class MessageEventListener implements ApplicationListener<MessageEvent> { 
public void onApplicationEvent(MessageEvent event) { 
MessageEvent msgEvt = (MessageEvent) event; 
System.out.println("Received: " + msgEvt.getMessage()); 
} 
} 

 

public class Publisher implements ApplicationContextAware { 
private ApplicationContext ctx; 
public static void main(String[] args) { 
ApplicationContext ctx = new ClassPathXmlApplicationContext( 
"classpath:events/events.xml"); 
Publisher pub = (Publisher) ctx.getBean("publisher"); 
pub.publish("Hello World!"); 
pub.publish("The quick brown fox jumped over the lazy dog"); 
} 
public void setApplicationContext(ApplicationContext applicationContext) 
throws BeansException { 
this.ctx = applicationContext; 
} 
public void publish(String message) { 
ctx.publishEvent(new MessageEvent(this, message)); 
} 
}

 

<bean id="publisher" class="com.apress.prospring3.ch5.event.Publisher"/> 
<bean id="messageEventListener" 
class="com.apress.prospring3.ch5.event.MessageEventListener"/>

 5.Accessing Resources

public static void main(String[] args) throws Exception{ 
ApplicationContext ctx = new ClassPathXmlApplicationContext( 
"classpath:events/events.xml"); 
Resource res1 = ctx.getResource("file:///d:/temp/test.txt"); 
displayInfo(res1); 
Resource res2 = ctx.getResource("classpath:test.txt"); 
displayInfo(res2); 
Resource res3 = ctx.getResource("http://www.google.co.uk"); 
displayInfo(res3); 
} 
private static void displayInfo(Resource res) throws Exception{ 
System.out.println(res.getClass()); 
System.out.println(res.getURL().getContent()); 
System.out.println(""); 
//getFile(), getInputStream(), or getURL()
}
6. Java Configuration
@Configuration 
public class AppConfig { 
// XML: 
// <bean id="messageProvider" 
class="com.apress.prospring3.ch5.javaconfig.ConfigurableMessageProvider"/> 
@Bean 
public MessageProvider messageProvider() { 
return new ConfigurableMessageProvider(); 
} 
// XML: 
// <bean id="messageRenderer" 
class="com.apress.prospring3.ch5.javaconfig.StandardOutMessageRenderer" 
// p:messageProvider-ref="messageProvider"/> 
@Bean 
public MessageRenderer messageRenderer() { 
MessageRenderer renderer = new StandardOutMessageRenderer(); 
// Setter injection 
renderer.setMessageProvider(messageProvider()); 
return renderer; 
} 
 

 

@Configuration 
@Import(OtherConfig.class) 
// XML: <import resource="classpath:events/events.xml") 
@ImportResource(value="classpath:events/events.xml") 
// XML: <context:property-placeholder location="classpath:message.properties"/> 
@PropertySource(value="classpath:message.properties") 
// XML: <context:component-scan base-package="com.apress.prospring3.ch5.context"/> 
@ComponentScan(basePackages={"com.apress.prospring3.ch5.context"}) 
@EnableTransactionManagement public class AppConfig { 
@Autowired 
Environment env; 
// XML: 
// <bean id="messageProvider" 
class="com.apress.prospring3.ch5.javaconfig.ConfigurableMessageProvider"/> 
@Bean 
@Lazy(value=true) //XML <bean .... lazy-init="true"/> 
public MessageProvider messageProvider() { 
// Constructor injection 
return new ConfigurableMessageProvider(env.getProperty("message")); 
} 
// XML: 
// <bean id="messageRenderer" 
class="com.apress.prospring3.ch5.javaconfig.StandardOutMessageRenderer" 
// p:messageProvider-ref="messageProvider"/> 
@Bean(name="messageRenderer") 
@Scope(value="prototype") // XML: <bean ... scope="prototype"/> 
@DependsOn(value="messageProvider") // XML: <bean ... depends-on="messageProvider"/> 
public MessageRenderer messageRenderer() { 
MessageRenderer renderer = new StandardOutMessageRenderer(); 
// Setter injection 
renderer.setMessageProvider(messageProvider()); 
return renderer; 
} 
} 

 7.ConfigurableEnvironment env = ctx.getEnvironment(); 

MutablePropertySources propertySources = env.getPropertySources(); 

8.JSR-330

@Named("messageRenderer") 
@Singleton 
public class StandardOutMessageRenderer implements MessageRenderer { 
@Inject 
@Named("messageProvider") 
private MessageProvider messageProvider = null; 
public void render() { 
if (messageProvider == null) { 
throw new RuntimeException( 
"You must set the property messageProvider of class:" 
+ StandardOutMessageRenderer.class.getName()); 
} 
System.out.println(messageProvider.getMessage()); 
} 
public void setMessageProvider(MessageProvider provider) { 
this.messageProvider = provider; 
} 
public MessageProvider getMessageProvider() { 
return this.messageProvider; 
} 
} 

 

 

 新书推荐《JavaEE开发的颠覆者: Spring Boot实战》,涵盖Spring 4.x、Spring MVC 4.x、Spring Boot企业开发实战。

 

京东地址:http://item.jd.com/11894632.html

当当地址:http://product.dangdang.com/23926195.html

亚马逊地址:http://www.amazon.cn/图书/dp/B01D5ZBFUK/ref=zg_bsnr_663834051_6 

淘宝地址:https://item.taobao.com/item.htm?id=528426235744&ns=1&abbucket=8#detail

 

或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。

 


 

 

分享到:
评论

相关推荐

    spring-boot-mybatis-plus数据层框架

    ### Spring Boot与MyBatis-Plus整合详解 #### 一、MyBatis-Plus概述 MyBatis-Plus(简称MP)是MyBatis的一个增强工具,在MyBatis的基础上进行了功能增强,但不改变原有的核心功能,旨在简化开发流程、提高开发效率...

    spring-framework-reference-4.1.2

    Dependencies and configuration in detail ........................................................... 38 Straight values (primitives, Strings, and so on) ........................................... 38 ...

    spring-framework-reference4.1.4

    Dependencies and configuration in detail ........................................................... 38 Straight values (primitives, Strings, and so on) ........................................... 38 ...

    spring-detail-demo:根据编码,请不要使用此项目

    本篇文章将基于“spring-detail-demo”项目,深入探讨Spring的核心特性——依赖注入(Dependency Injection,简称DI)以及面向切面编程(Aspect-Oriented Programming,简称AOP),旨在帮助开发者更全面地理解和运用...

    Spring5.0中文开发手册

    - **3.4.2 Dependencies and configuration in detail** - 详细讨论了依赖项的配置和注入细节。 - **3.4.3 Using depends-on** - 使用`depends-on`属性确保某些bean在其他bean之前初始化。 - **3.4.4 Lazy-...

    Spring和Mybatis整合英文文档翻译.pdf

    MyBatis-Spring will generate the implementation at runtime.Now, let's discuss each component in detail. 1. **SqlSessionFactory**: The SqlSessionFactory is the central object in MyBatis that creates ...

    Spring.Cookbook.1783985801.epub

    Use the latest configuration style and web improvements in Spring 4 to write optimized code Build full-featured web applications such as Spring MVC applications efficiently that will get you up and ...

    Spring.MVC.Cookbook.1784396419

    Spring MVC is a lightweight application framework that comes with a great configuration by default. Being part of the Spring Framework, it naturally extended and supported it with an amazing set of ...

    原创 Struts Spring Hibernate (SSH) 整合实例

    &lt;plug-in className="org.apache.struts2.spring.StrutsSpringPlugin"&gt; &lt;!-- 配置Spring上下文 --&gt; &lt;set-property property="configurationClass" value="org.springframework.web.context.ContextLoaderListener...

    springMVC整合DWR3.0 实例

    ### SpringMVC整合DWR3.0 实例详解 #### 一、前言 随着Web技术的不断发展,前后端分离的架构模式越来越受到开发者的青睐。...希望本文能为您的项目带来帮助,也欢迎各位提出宝贵意见,共同学习进步。

    单点登录源码

    SpringMVC | MVC框架 | [http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc](http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc) ...

    SpringBoot整合Mybatis连接数据库demo

    2. **添加依赖** 在`pom.xml`文件中,添加Mybatis和Thymeleaf的相关依赖。例如: ```xml &lt;groupId&gt;org.mybatis.spring.boot &lt;artifactId&gt;mybatis-spring-boot-starter &lt;version&gt;2.2.2 &lt;groupId&gt;org....

    MyBatisPlus插件扩展_PerformanceInterceptor性能分析插件的使用示例代码

    在Spring Boot项目中,通常会在`mybatis-plus-config.xml`或`application.yml`中进行配置。以下是配置示例: ```xml &lt;!-- mybatis-plus-config.xml 示例 --&gt; &lt;configuration&gt; &lt;!-- 可选,打印执行的sql语句的...

    springboot连接数据库

    @Configuration public class FreemarkerConfig { @Bean public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer....

Global site tag (gtag.js) - Google Analytics