Java Spring框架 的简单搭建

作者:清风拂面 | 创建时间: 2023-06-15
基于IoC/DI的一个对象容器,管理系统中的对象的创建和装配过程. IoC: 控制反转 DI: 依赖注入...
Java Spring框架 的简单搭建

操作方法

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

温馨提示

自动装配 在beans上通过设置属性 default-autowire来实现自动装配 byName: 根据bean的id和set方法的名称匹配来自动装配 byType: 根据bean的类型和set方法的参数类型来匹配装配(如果找到多个bean会报错)
点击展开全文

更多推荐