applicationContext.xml文件的简化配置
在使用spring时,我们会在applicationContext.xml文件中配置很多东西。如果项目很大,那么applicationContext.xml中的东西就会非常多,且非常凌乱,为了解决这个问题,可以把applicationContext.xml进行分模块简化配置;
比如dao包下的所有的类在application—dao.xml中配置;
service包下的所有类在application-service.xml中配置;等等
模块分化好了,就要在一个配置文建中建立一个花名册,把所有的模块的地址放进去(即导入xml文件),就可以通过花名册找到所有的模块,我们一般把这个花名册放在applicationContext.xml文件中,且这个文件只放花名册,这样整个体系就会显得尤为清晰。applicationContext.xml文件的配置如下:
<import resource="classpath:application-dao.xml"/>
<import resource="classpath:application-service.xml"/>
集成Spring+mybatis(有mybatis.cfg.xml)
- 数据源由spring引入,放入application-dao.xml中,因为这个dao包下放的类是与数据库打交道的;
- mybatis.cfg.xml中有mybatis的配置信息;mybatis的配置信息有:
- 配置日志输出形式
- 配置别名
- 配置分页插件
- 加载mybatis数据库操作的映射文件。譬如UserMapper.xml,里面配置的是一些数据库操作;
如下是mybatis.cfg.xml文件的配置:
<configuration>
<!-- 配置日志输出形式 -->
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
<!-- 配置别名 -->
<typeAliases>
<package name="com.sxt.domain"/>
</typeAliases>
<!-- 配置分页插件 -->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
<!-- 加载mybait数据库操作的映射文件 -->
<mappers>
<mapper resource="mapper/UserMapper.xml" />
</mappers>
</configuration>
- Spring+mybatis集合不再使用SqlSessionFactoryBuilder获取SqlSessionFactory对象;org.mybatis.spring.SqlSessionFactoryBean中封装了获取SqlSessionFactory的方法,可直接从这个类的对象获取,有对象创建,就要想到用到IOC容器,所以此处SqlSessionFactory的声明也配置文件中;放在application-dao.xml中;
- 获取SqlSessionFactory对象后,要对接口进行映射,给这个接口创建代理对象;在mybatis中映射的步骤如下
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = builder.build(SessionUtil.class.getClassLoader().getResourceAsStream("mybatis.cfg.xml"));
SqlSession session = sqlSessionFactory.openSession();
// UserMapper为接口
UserMapper mapper = session.getMapper(UserMapper.class);
以上是Java代码,因为SqlSessionFactory是在xml文件中配置的,所以接口的映射无法用Java代码来写。但是可以通过xml文件配置。配置好后也放在application-dao.xml中;
5. 其他类的对象创建这里采用注释的方法,所以要给进行注释扫描
综合以上分析,得出配置文件的思路,根据这个思路配置文件,文件的配置方法如下:
1. application-dao.xml的配置
<context:component-scan
base-package="com.young.dao.impl"></context:component-scan>
<context:property-placeholder location="db.properties" system-properties-mode="FALLBACK"/>
<!-- 声明dataSource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!-- 声明sessionFactory 并注入mybatis.cfg.xml-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis.cfg.xml"/>
</bean>
<!-- 扫描mapper接口 这是一个固定写法 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.young.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
2. application-service.xml的配置
<context:component-scan base-package="com.young.service.impl"></context:component-scan>
3. application-action.xml的配置
<context:component-scan base-package="com.young.action"></context:component-scan>
4. applicationContext.xml的配置
<import resource="classpath:application-dao.xml"/>
<import resource="classpath:application-service.xml"/>
<import resource="classpath:application-action.x
为接口创建代理对象,需要从映射文件中读取相关的信息,所以还需要配置映射文件,映射文件和mybatis一样
5.配置UserMapper.xml文件
<mapper namespace="com.young.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.young.domain.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="tg_age" jdbcType="INTEGER" property="age" />
</resultMap>
<select id="selectAll" resultType="User">
select * from user
</select>
</mapper>
6.配置数据操作数据的文件db.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatisuseUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=ky123456
7.配置日志文件log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, <u>stdout</u>
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] -
%m%n
把以上这些配置文件配置好后放在一个与src平级的文件夹下,假设给这个文件夹取名为resource;
注意:resource文件夹创建是不能用Folder,应该用Source Folder,否则会找不到配置文件
配置文件的分布如下:
接下来创建Java类
- 创建User.java
public class User {
private Integer id;
private String name;
private Integer tg_age;
public User(Integer id, String name, Integer tg_age) {
super();
this.id = id;
this.name = name;
this.tg_age = tg_age;
}
public User(String name, Integer tg_age) {
this.name = name;
this.tg_age = tg_age;
}
public User() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
//接下来是一些setget方法,以及toString方法的改写,此处省略
- 创建UserMapper.java接口
public interface UserMapper {
public List<User> selectAll();
}
3.创建UserDao.java接口
public interface UserDao {
public List<User> queryAll();
}
- 创建UserDao接口的实现类UserDaoImpl.java,使用注解创建对象
@Component
public class UserDaoImpl implements UserDao{
@Autowired
private UserMapper userMapper;
@Override
public List<User> queryAll() {
return userMapper.selectAll();
}
}
- 创建UserService接口
public interface UserService {
public List<User> queryAll();
}
6.创建UserService接口的实现类UserServiceImpl,使用注解创建对象
@Component
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> queryAll() {
return userDao.queryAll();
}
}
- 创建UserAction类,使用注解创建对象
@Component
public class UserAction {
@Autowired
private UserService userService;
public List<User> queryAll() {
return userService.queryAll();
}
}
- 测试
public class Test {
public static void main(String[] args) {
ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
UserAction bean = app.getBean(UserAction.class);
List<User> queryAll = bean.queryAll();
for (User user : queryAll) {
System.out.println(user);
}
}
}
在测试的过程中,如果使用到的类没有实例化,就会抛异常,譬如UserServiceImpl没有实例化就会报如下异常:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.young.service.impl.UserServiceImpl' available
这里只示范了一个数据库操作,其他数据库操作的方法与上面类似
集成Spring+mybatis(没有mybatis.cfg.xml)
和有mybatis.cfg.xml的集成不同的是,没有mybatis.cfg.xml的集成没有mybatis.cfg.xml配置文件;
mybatis.cfg.xml文件中的信息是读取到SqlSession中的,所以在没有mybatis.cfg.xml文件的情况下,里面的一些信息就需要放到application-dao.xml文件中的sqlSessionFactory对象的属性中;application-dao.xml文件的配置方法如下:
<!-- 引入db.properties -->
<context:property-placeholder location="classpath:db.properties" system-properties-mode="FALLBACK"/>
<!-- 声明dataSource -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 注入连接属性 -->
<property name="driverClassName" value="${driverClassName}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
</bean>
<!-- 声明sessionFactory 并注入mybatis.cfg.xml-->
<!--
MyBatis是先创建SqlSessionFactoryBuilder对象,再通过SqlSessionFactoryBuilder对象得到SqlSessionFactory对像;
此处的SqlSessionFactory对像是在
org.mybatis.spring.SqlSessionFactoryBean封装好的,直接拿,无须再管SqlSessionFactoryBuilder
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 注入mapper.xml 这种类型的xml文件可能会有多个,所以要用数组装 -->
<property name="mapperLocations">
<array>
<value>classpath:mapper/UserMapper.xml</value>
</array>
</property>
<!-- 插件 插件可能也有多个,所以也用数组装 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor"></bean>
</array>
</property>
<!-- 注入别名 -->
<property name="typeAliasesPackage" value="com.young.domain"></property>
</bean>
<!-- 扫描mapper接口 这是一个固定写法 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入mapper接口所在的包 -->
<property name="basePackage" value="com.young.mapper"></property>
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
这种集成方法除了这个地方有改变,其他地方都是一样的;