版权声明:本文为博主原创作品,如需转载请标明出处。 https://blog.csdn.net/weixin_42162441/article/details/82704209
记录一次 Java 类配置集成的方式
自动的配置 DispatcherServlet 和 Spring 应用上下文
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class };
} //其他 bean 的配置类
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebConfig.class};
}//包含 Web 组件的 bean
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}//将 DispatcherServlet 映射到"/"
}
RootConfig 的内容
:配置了 mybatis 的SqlSessionBean 和 MapperScannerConfigurer ,其中前者我配置在了 XML 中,用 ImportResource导入。
@ImportResource("classpath:mybatis-config.xml")
@Configuration
public class RootConfig {
@Bean
public MapperScannerConfigurer mapperScanner() {
MapperScannerConfigurer mapperScanner =
new MapperScannerConfigurer();
mapperScanner.setBasePackage("cn.iunote.web.mapper");
return mapperScanner;
}
}
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean id="datasource" class="org.apache.ibatis.datasource.pooled.PooledDataSource" >
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="52wmssdr" />
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"></property>
<property name="mapperLocations">
<array>
<value>classpath:cn/iunote/web/mapper/bookMapper.xml</value>
</array>
</property>
</bean>
</beans>
WebConfig 的内容
@Configuration
@EnableWebMvc //等同于在 XML 中配置<mvc:annotation-driven/>启用注解驱动的 SpringMVC
@ComponentScan(basePackages= {"cn.iunote.web.controller","cn.iunote.web.DAO"})
public class WebConfig {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
}