1. 利用maven搭建ssm,这里参考了一篇优秀的文章:
2. 预期搭建好的项目目录如下:![项目工程目录](https://img-blog.csdnimg.cn/img_convert/c0a07d81e021c0efa226c36c6596c038.png#pic_center)
3. maven工程中默认web.xml不能访问到main/resources下的配置文件,在pom中利用如下代码将resources目录打包到WEB-INF下【要放到标签下】
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
4. 设置两个容器,一个Spring容器,配置文件为applicationContext.xml,一个SpringMVC容器,配置文件为spring-MVC.xml
其中,springMVC只处理标记了Controller注解的东西,引入如下代码:
<context:component-scan base-package="com.xiaohu.controller" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
**注意这里要加入use-default-filters="false"
,因为默认行为是扫描所有,所以要先关掉默认行为
spring处理余下的东西,引入如下代码:
<context:component-scan base-package="com.xiaohu.controller" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
注意这里仍然是要扫描所有东西的,只不过去掉了Controller,所以不用加use-default-filters="false"
5. 对Spring的再理解
- Q: Spring的xml文件配置核心都是利用配置文件实现对象创建和属性注入,那真正用到这些对象我要去哪里拿呢
A:利用getBean()
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
Book book = context.getBean("book", Book.class);
其实也可以利用注解直接AutoWired
,这样也会把xml文件中已经注入的属性和创建的对象装配好,这个角度看来注解和xml配置是不冲突的,可以理解为xml进行预先的配置然后注解在实际工程中将其快速装配。但是有一点需要注意的是,用AutoWired
自动装配一定不能用new
,否则会失效。
6. 配置druid连接池时遇到的坑
-
<property name="driverClassName" value="${driverClassName}" />
这里property name必须写成
driverClassName
-
一开始是mysql-config部分出了问题,显示没有mybatis-pageHelper,导入maven后发现还是出了问题,原来是5.0版本有一些更新导致的,详情请见:
mybatis pageHelper 5.0的坑