操作方法
1. spring框架搭建
加入jar包 SPRING_HOME/dist下的: org.springframework.asm-3.1.3.RELEASE.jar org.springframework.beans-3.1.3.RELEASE.jar org.springframework.context-3.1.3.RELEASE.jar org.springframework.core-3.1.3.RELEASE.jar org.springframework.expression-3.1.3.RELEASE.jar 加入common-logging.jar包
加入配置文件 在src下创建一个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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> </beans>
将对象交给Spring管理 在beans中通过bean标签来配置将要被spring管理的类 <bean id="userDaoImpl4MySQL" class="com.direct.dao.impl.UserDaoImpl4MySQL"></bean>
从spring容器中获取对象 1. 加载配置文件 BeanFactory bf = new ClassPathXmlApplicationContext("applicationContext.xml"); 2. 获取对象(传入在xml中配置的bean的对应id) UserService us = (UserService) bf.getBean("userService");
sping的注入
自定义类型转换器
编写一个转换器类,继承与PropertyEditorSupport,并重写其中的setAsText方法进行转换 转换后调用本类的setValue来设置值
配置到spring中来使用 <!-- 配置一个自定义类型转换器 --> <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <!-- 配置类型转换映射 --> <entry key="java.util.Date"> <bean class="com.direct.converter.DateConverter" /> </entry> </map> </property> </bean>
分文件管理配置 定义相同规则的配置文件名称,加载时用*来适配 applicationContext*.xml