SpringMVC/Hibernate项目实践一
SpringMVC/Hibernate项目实践二
SpringMVC/Hibernate项目实践三
第二步,引入Spring并实现IoC特征

- 在web.xml 中添加跟spring相关的配置信息
web.xml
</welcome-file-list>
<!--加载Spring的配置文件到上下文中去 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/applicationContext.xml
</param-value>
</context-param>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 字符集过滤 -->
- 在resource中创建applicationContext.xml
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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="online.shixun.project">
<!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
</beans>
- 创建包service,在其中创建UserService.java
UserService.java
@Service
public class UserService {
public String test(){
return "hello";
}
}
- 调整UserController.java,体现Spring IoC
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value="hello")
public String hello(){
return userService.test();
}
}
现在我们启动一下项目,就能体现出IoC的特征了。
网友评论