spring基本配置

spring基本配置

具体文件形式:

applicationContext.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- 包含整体通用配置 -->

<!-- 包含其他文件的配置 -->

<!-- 导入helloworld.xml -->

<!--resource来源于classpath的根路径-->

<!--错误写法:<import resource="classpath:helloworld.xml"></import>

原因在于强调在编译后,classpath不存在该文件

-->

<import resource="classpath:springbean/helloworld.xml"></import>

</beans>

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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd" >

<bean id="helloworld" class="springbean.helloworld">

<property name="username" value="洲洲"></property>

</bean>

</beans>

helloworld类

package springbean;

public class helloworld {

private String username;

public helloworld(){

System.out.println("所谓的焦虑就是书读得太少,而想得又太多");

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public void sqyhello(){

System.out.println("你好世界,我的名字是"+username);

}

}

test测试类

package springbean;

import org.junit.Test;

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;

public class test {

@Test

public void test(){

//classpath获取路径

Resource resource= new ClassPathResource("applicationContext.xml");

//获取资源文件创建spring容器

BeanFactory factory=new XmlBeanFactory(resource);

//创建对象

helloworld world=(helloworld) factory.getBean("helloworld");

world.sqyhello();

}

}

结果为:

猜你喜欢

转载自blog.csdn.net/zhouzhou_98/article/details/84595035