本章为Spring注入Bean的一个简单例子
想要注入一个bean到Spring并使用需要以下三步:
- 创建bean,即你所要注入到Spring中的类
- 在xml配置文件中注册bean(也可以使用注解)
- 通过beanFactory(加载配置配置文件,解析配置文件)获得bean
Spring注入Bean小例子---Hello World
创建helloworld类
public class Hello{ public void say(){ System.out.println("Hello World!"); } }
在spring-config.xml(名字可任意)文件中配置bean(更多配置属性可以查看笔者的另一篇文章)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="hello" class="Hello" /> </beans>
在应用中获得bean
public class MyFirstTest { @Test public void testBean() { ApplicationContext ac = new ClassPathXmlApplicationContext("spring-config.xml"); Hello my = (Hello) ac.getBean("hello",Hello.class); my.say(); } }