1. 程式人生 > >spring基本配置

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();

}

}

 

 

 

結果為: