spring基于XML的IOC环境搭建和入门

91 阅读1分钟

MessageService.java:

public class MessageService {

    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }

}

spring-config.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">
    <!-- 配置service
            <bean> 配置需要创建的对象
            id :用于之后从spring容器获得实例时使用
            class :需要创建实例的全限定类名
            property:类中的成员
            property name  成员的名称
            property value 成员的值
        -->
<bean id="messageService" class="com.spring.MessageService">
    <property name="message" value="Hello Spring"/>
</bean>
</beans>

测试类:

public class SpringTest {
    @Test
    public void test(){
        //获取应用上下文对象(Spring容器)
        ApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
        //从容器中获取java对象
        //下面这个两种方式都可以
       // MessageService service=(MessageService)context.getBean("messageService");
        MessageService service=context.getBean("messageService",MessageService.class);
        String message=service.getMessage();
        System.out.println(message);
    }
}

结果:

Hello Spring

从工厂中获取对象的方法:

ApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
//根据id获取
MessageService service=(MessageService)context.getBean("messageService");
//根据id及类信息获取,无需转型
MessageService service=context.getBean("messageService",MessageService.class);
//
MessageService service=context.getBean(MessageService.class);