超级通道:Spring代码实例系列-绪论
这是Spring框架中的hello world实例,简单的展示了以下技术:
1. 注入bean
2. spring的xml配置文件
3. setter注入
1.目录
project
\---src
\---main
\---java
| \---pers
| \---hanchao
| \---helloworld
| \---App.java
| \---Hellospring.java
\---resources
\---spring-config
\---spring-helloworld.xml
2.App.java
package pers.hanchao.helloworld;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* <p>hellospring</p>
* @author hanchao 2018/1/7 12:15
**/
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config/spring-helloworld.xml");
HelloSpring helloSpring = (HelloSpring) context.getBean("helloSpring");
helloSpring.printHello();
}
}
3.spring-helloworld.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloSpring" class="pers.hanchao.helloworld.HelloSpring">
<property name="name" value="hanchao"/>
</bean>
</beans>
4.HelloSpring.java
package pers.hanchao.helloworld;
/**
* <p>springhello:通过xml配置bean,注入值到bean</p>
* @author hanchao 2018/1/7 12:18
**/
public class HelloSpring {
private String name;
public void setName(String name) {
this.name = name;
}
public void printHello(){
System.out.println("hello spring:" + this.name);
}
}
5.result
hello spring:hanchao