spring --(1)入門

spring4.x中文文檔
http://spring.cndocs.tk/index.html
開濤的spring4.1介紹
http://jinnianshilongnian.iteye.com/blog/2102278
spring4框架參考手冊
http://www.open-open.com/doc/view/b15f500781184c4c9f731577a9b83746
spring4參考中文手冊
http://www.docin.com/p-1426181729.html
spring官網
http://projects.spring.io/spring-framework/
maven下載路徑
http://mvnrepository.com/
sts插件下載
http://spring.io/tools/sts/allhtml

<dependencies> 
    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-context</artifactId> 
        <version>4.3.0.RELEASE</version> 
    </dependency> 
</dependencies>

我下載的jar包以下
輸入圖片說明
開始spring的第一個示例
1.新建一個java project
2.導入spring的5個jar包,同時須要導入commons-logging.jar包,由於這個是spring的依賴包
3.建一個HelloWorld類java

public class HelloWorld {
	
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public void hello() {
		System.out.println("hello:"+name);
	}
	
}

4.新建一個Main類spring

public class Main {
	
	public static void main(String[] args) {
		
		//常規作法
		//建立實例對象
		HelloWorld helloWorld = new HelloWorld();
		//給對象賦值
		helloWorld.setName("test");
		//調用對象方法
		helloWorld.hello();

		
		//使用spring
		//1.建立spring的ioc容器對象,即調用配置文件中全部類的構造器方法,同時給其屬性設值
		@SuppressWarnings("resource")
		ApplicationContext ctx = new ClassPathXmlApplicationContext("appli.xml");
		//2.從ioc容器中獲取bean實例,即上述配置文件中bean 的 id
		HelloWorld helloWorld2 =(HelloWorld) ctx.getBean("helloWorld");
		//3.調用示例方法
		helloWorld2.hello();
	}

}

5.appli.xml配置文件以下app

<?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 -->
	<bean id="helloWorld" class="com.test.bean.HelloWorld">
		<property name="name" value="spring"></property>	
	</bean>

</beans>
相關文章
相關標籤/搜索