编写第一个Spring程序
HelloWorldBean实现类:
Spring XML配置文件ioc-config.xml:
测试类:
步骤小结
①利用XmlBeanFactory读取xml配置文件并建立BeanFactory实例
②BeanFactory依据配置文件完成依赖注入
③通过getBean()方法指定Bean名称取得Bean实例
HelloWorld接口:
- /**
- *
- * @Copyright(C),2009-2010 SISE Java Team.
- * @Author:easinchu
- * @Email:easinchu@gmail.com
- * @Description:
- */
- public interface HelloWorld {
- public void sayHello();
- }
HelloWorldBean实现类:
- /**
- *
- * @Copyright(C),2009-2010 SISE Java Team.
- * @Author:easinchu
- * @Email:easinchu@gmail.com
- * @Description:
- */
- public class HelloWorldBean implements HelloWorld{
- private String helloWorld;
- public void setHelloWorld(String helloWorld) {
- this.helloWorld = helloWorld;
- }
- public void sayHello() {
- System.out.println(helloWorld);
- }
- }
Spring XML配置文件ioc-config.xml:
- <bean id="helloWorldBean" class="cn.com.sise.firstapp.HelloWorldBean">
- <property name="helloWorld">
- <value>Hello,Welcome To Spring World!</value>
- </property>
- </bean>
测试类:
- import org.springframework.beans.factory.BeanFactory;
- import org.springframework.beans.factory.xml.XmlBeanFactory;
- import org.springframework.core.io.ClassPathResource;
- import org.springframework.core.io.Resource;
- /**
- *
- *@Copyright(C),2009-2010 SISE Java Team.
- *@Author:easinchu
- *@Email:easinchu@gmail.com
- *@Description:采用Spring的BeanFactory构造IoC容器.
- */
- public class FirstSpringDemo {
- public static void main(String []args) {
- //-----------BeanFactory IoC容器---------------------//
- //从classpath路径上装载XML的配置信息
- Resource resource = new ClassPathResource("ioc-config.xml");
- //实例化IOC容器,此时容器并未实例化beans-config.xml所定义的各个受管bean.
- BeanFactory factory = new XmlBeanFactory(resource);
- /
- //获取受管bean
- HelloWorld hello = (HelloWorld)factory.getBean("helloWorldBean");
- hello.sayHello();
- }
- }
步骤小结
①利用XmlBeanFactory读取xml配置文件并建立BeanFactory实例
②BeanFactory依据配置文件完成依赖注入
③通过getBean()方法指定Bean名称取得Bean实例


728

被折叠的 条评论
为什么被折叠?



