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