1. 程式人生 > >spring框架初級搭建

spring框架初級搭建

1.匯入jar包
在這裡插入圖片描述
2.編寫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"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="userService" class="com.huida.demo.UserServiceImpl" destroy-method="destroy" init-method="init">
		<property name="name" value="張三"></property>
	</bean>
	<!-- 依賴注入 -->
	<bean id="userDao" class="com.huida.demo1.UserDao"></bean>
	<bean id="userService1" class="com.huida.demo1.UserService">
	    <property name="dao" ref="userDao"></property>
	</bean>
	<!-- 構造方法的依賴注入 -->
	<bean id="car1" class="com.huida.demo2.Car1">
	    <constructor-arg name="cname" value="QQ"></constructor-arg>
	    <constructor-arg name="price" value="25000"></constructor-arg>
	</bean>
	<!-- 採用p名稱空間注入 -->
	<!-- <bean id="car2" class="com.huida.demo2.Car2" p:cname="保時捷" p:price="1500000"></bean> -->
	<!-- 使用SPEL注入方式
	<bean id="car2" class="com.huida.demo2.Car2" p:cname="保時捷" p:price="1500000">
	    <property name="cname" value="#{'拖拉機'}"></property>
	    <property name="price" value="#{2000}"></property>
	</bean> -->
    <!-- 注入集合 -->
    <bean id="user" class="com.huida.demo2.User">
        <property name="arrs">
           <value>哈哈</value> 
          
           
        </property>
        
    </bean>

</beans>

3.程式碼測試
UserService

public interface UserService {
	public void sayHello();
}

UserServiceImpl

public class UserServiceImpl implements UserService{

	private String name;
	
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public void sayHello() {
		System.out.println("hello"+name);
		
	}
	public void init(){
		System.out.println("物件被建立了");
	}
	public void destroy(){
		System.out.println("物件被銷燬了");
	}
}

Demo

public class Demo {
	@Test
	public void run(){
		//建立工廠,載入核心配置檔案
		ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
		//從工廠中獲取物件
		UserService usi=(UserServiceImpl)ac.getBean("userService");
		//呼叫方法執行
		usi.sayHello();
		//關閉工廠
		ac.close();
	}
}

可以在web.xml中配置spring監聽器,只加載一次配置檔案

		 <listener>
            <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
         </listener>
         <context-param>
            <param-name>contextconfiglocation</param-name>
            <param-value>classpath:applicationcontext.xml</param-value>
         </context-param>
//加完監聽器後Web的工廠方式
		ServletContext servletContext=ServletActionContext.getServletContext();
		WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(servletContext);
		context.getBean("service");