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

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-framework-reference-4.1.2

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

    Learning.Spring.Application.Development.1783987367

    Chapter 2: Inversion Of Control In Spring Chapter 3: Dao And Jdbc In Spring Chapter 4: Hibernate With Spring Chapter 5: Spring Web Mvc Framework Chapter 6: Spring Security Chapter 7: Spring Testing ...

    spring-framework-reference4.1.4

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

    Spring.Boot.Cookbook.1785284150

    Spring Boot is Spring's convention-over-configuration solution. This feature makes it easy to create Spring applications and services with absolute minimum fuss. Spring Boot has the great ability to ...

    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 ...

    Pro Spring 3

    ■ Chapter 5: Spring Configuration in Detail ........................................................113 ■ Chapter 6: Introducing Spring AOP .............................................................

    单点登录源码

    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) ...

    Advanced.Java.EE.Development.with.WildFly.1783288906

    In Detail This book starts with an introduction to EJB 3 and how to set up the environment, including the configuration of a MySQL database for use with WildFly. We will then develop object-relational...

    .Advanced.Java.EE.Development.with.WildFly.1783288906

    In Detail This book starts with an introduction to EJB 3 and how to set up the environment, including the configuration of a MySQL database for use with WildFly. We will then develop object-relational...

    Salesforce.Reporting.and.Dashboards.178439467X

    Take advantage of creating reports and dashboards in the Salesforce mobile app, updated with Spring '15 release A concise and informative guide to solve all your reporting woes Who This Book Is For ...

    雷达技术知识

    Committee in Charge: W. Andrew Marcus, Chair Patricia F. McDowell Accepted by: Dean of the Graduate School © 2009 John Thomas English 111 IV An Abstract of the Thesis of John Thomas English in the ...

Global site tag (gtag.js) - Google Analytics