Spring:XML配置文件装配Bean

这种方式基本全都是由XML来描述,真正写起来XML内容十分多,直接来个简单例子

定义一个Hello类

package com.maoxiaomeng.xmlconfig;

/**
* Copyright (C), 2014-2018, maoxiaomeng.com
* FileName: Hello
* Author: lihui
* Date: 2018/6/24 下午7:08
*/

public class Hello {
private String message;

public Hello(String message) {
this.message = message;
}

public String getMessage() {
return message;
}
}

一个构造方法传一个message参数,一个get方法返回message

自行配置一个xml文件my.xml

这里<beans>是所有Spring配置文件的根元素,通过<bean>声明一个bean,创建这个bean的类通过class属性来指定,同时最好自定义设置一个id

通常bean id设置为对应类名第一个字母小写,class属性一般带上对应package

Spring会从这里获取信息来创建bean

从Hello类的构造方法可以看到,Hello bean定义了一个接受String message的构造函数,通过<constructor-arg>来指定传入构造函数的String类型参数

<?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="hello" class="com.maoxiaomeng.xmlconfig.Hello">
<constructor-arg value="Hello World" />
</bean>
</beans>

此时当Spring遇到<bean>元素,会创建一个Hello类型实例,<constructor-arg>元素告诉Spring要将一个ID为hello的bean引用传递到Hello的构造方法中

下面定义个main执行下

package com.maoxiaomeng.xmlconfig;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* Copyright (C), 2014-2018, maoxiaomeng.com
* FileName: Main
* Author: lihui
* Date: 2018/6/24 下午6:49
*/


public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("my.xml");
Hello hello = (Hello)context.getBean("hello");
hello.getMessage();
}
}

Spring通过应用上下文Application Context加载xml文件,装载bean的定义并组装起来,然后通过getBean并获取Hello类型的引用,最后调用getMessage方法

或者通过JUnit测试

package com.maoxiaomeng.xmlconfig;

import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
* Copyright (C), 2014-2018, maoxiaomeng.com
* FileName: HelloTest
* Author: lihui
* Date: 2018/6/24 下午7:47
*/

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:my.xml")
public class HelloTest extends TestCase {

@Autowired
private Hello hello;

@Test
public void testSayMessage() {
assertEquals("Hello World", hello.getMessage());
}
}

用了JUnit的@RunWith注解来说明测试类的运行者,用了@ContextConfiguration注解用来指定Spring配置信息来源

发表回复