Spring------IOC&DI

一、Spring?

  Spring兴起:2003年,由Rod Johnson创建。总的来说,Spring Framwork从它诞生至今都一直为人所称道,它的伟大之处自此可见一斑。

  核心:IOC&AOP

  • IOC

  全称:Inersion of control-->控制反转。把对象的创建工作交给框架(有意取代EJB)。

  IOC和DI:两个概念其实都是阐述同一个内容

  • AOP

  Aspect Oriented Programming的缩写,意为:面向切面编程

  官网:https://spring.io/

二、如何入门(整合Servlet)?

  • 准备jar包:官网下载资源, 导入Core Container中的 4个jar包:beans | code | context | expression+4个日志jar包+spring-web-xxx.jar
  • 配置文件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.xsd">
    <bean name="us" class="com.gaga.service.serviceimp.UserServiceImp">
        <property name="name" value="张三"></property>
    </bean>
</beans>
  • Servlet

  public class ServletDemo extends HttpServlet {    @Override

   
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    //这里通过工具类创建工厂,解决:每次请求过来都会解析xml, 创建工厂。如果xml内容很多,就比较的耗时。 WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); UserService userService = (UserService) context.getBean("us"); userService.saveUser(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
  • UserServiceImp

 

public class UserServiceImp implements UserService {

    private String name;
    public void setName(String name) {
        this.name = name;
    }
 
    public void setName(String name) {
        this.name = name;
    }

    public void saveUser() {
        System.out.println("UserServiceImp收到了请求--name-------" + name );
    }
}
  • web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
    
        <servlet>
            <servlet-name>S</servlet-name>
            <servlet-class>com.gaga.test.ServletDemo</servlet-class>
        </servlet>

    <!-- 配置监听器 定义监听器, 然后在监听器里面创建工厂 , 存储工厂到一个地方去,以便所有的servlet都能使用到工厂。 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 告诉监听器,配置文件在哪里 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <servlet-mapping> <servlet-name>S</servlet-name> <url-pattern>/demo</url-pattern> </servlet-mapping> </web-app>

  

 

posted @ 2018-01-31 21:51  三毛他哥  阅读(187)  评论(0编辑  收藏  举报