Spring 下载地址:
http://www.springsource.org/download最少依赖包 commons-logging-1.1.1.jar spring.jar (我增加了log4j让执行步骤输出更详细).
1. Hello.java1 package alex.study.spring.hello;
2
3 public interface Hello {
4 void salute();
5 }
2. HelloImp.java 1 package alex.study.spring.hello;
2
3 public class HelloImp implements Hello {
4
5 private String name;
6 private String send;
7
8 public HelloImp(String name, String send) {
9 this.name = name;
10 this.send = send;
11 }
12
13 public void setName(String name) {
14 this.name = name;
15 }
16
17 public void setSend(String send) {
18 this.send = send;
19 }
20
21 @Override
22 public void salute() {
23 System.out.println(name + " : " + send);
24 }
25
26 }
27
3. spring-hello.xml (跟以上类放在同一包中)
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
6
7 <!-- 构造方法注入Bean -->
8 <bean id="helloimp" class="alex.study.spring.hello.HelloImp">
9 <!-- 告诉Spring通过构造函数给Bean属性赋值 -->
10 <constructor-arg value="alex" />
11 <constructor-arg value="Hello World!"/>
12 </bean>
13 </beans>
14
4. log4j.properties (src目录下)
1 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
2 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
3 log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm:ss} [%5p] %c{1} - %m%n
4
5 log4j.rootLogger=DEBUG, stdout
6
7 log4j.category.com.springinaction=DEBUG
8 log4j.category.org.springframework=DEBUG
9
5. HelloApp.java
1 package alex.study.spring.hello;
2
3 import org.springframework.beans.factory.BeanFactory;
4 import org.springframework.beans.factory.xml.XmlBeanFactory;
5 import org.springframework.core.io.ClassPathResource;
6
7 public class HelloApp {
8 public static void main(String[] args) {
9 //初始化Bean工厂
10 BeanFactory factory = new XmlBeanFactory(new ClassPathResource("alex/study/spring/hello/spring-hello.xml"));
11 Hello hello = (Hello) factory.getBean("helloimp"); //从Bean工厂获取xml文件配置的ID为helloimp Bean.
12
13 hello.salute();
14 }
15 }
16
6. 输出结果
1
2 14:45:38 [DEBUG] DefaultBeanDefinitionDocumentReader - Loading bean definitions
3 14:45:38 [DEBUG] XmlBeanFactory - Creating shared instance of singleton bean 'helloimp'
4 14:45:38 [DEBUG] XmlBeanFactory - Creating instance of bean 'helloimp'
5 14:45:38 [DEBUG] XmlBeanFactory - Eagerly caching bean 'helloimp' to allow for resolving potential circular references
6 14:45:38 [DEBUG] XmlBeanFactory - Finished creating instance of bean 'helloimp'
7 alex : Hello World!