1. 程式人生 > >Spring 簡單的 IOC

Spring 簡單的 IOC

實現簡單的Spring IOC 依賴注入

第一步:增加maven依賴 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.yxl.spring01</
groupId
>
<artifactId>spring_01</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.5.RELEASE</
version
>
</dependency> </dependencies> </project>

Hello.java



第二步 :編寫一個簡單的pojo類
package org.spring01;
public class Hello {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void show
() { System.out.println(name); } }

第三步 :編寫Spring配置檔案,該檔案路徑在根目錄下。src/main/java/beans.xml beans.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">
 <!--name是別名,可以有多個。 -->
  <bean id="hello" name="h1,h2,h3" class='org.spring01.Hello'>
  	<property name="name" value="張三"></property>
  </bean>
</beans>

第四步:編寫測試類 Test.java

package org.spring01;

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

public class Test {
	public static void main(String[] args)  {
		try {
			//解析beans.xml檔案生成管理相應的bean物件
			ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
			//根據bean名稱獲取Hello物件
			Hello he=(Hello) context.getBean("h1");
			he.show();
		} catch (BeansException e) {
			e.printStackTrace();
		}
	}
}

備註:bean的name屬性可以有多個。用空格或者逗號分割。