zoukankan      html  css  js  c++  java
  • Spring入门初体验

    Spring其实就是一个容器,让我们更方便的拿到想要的对象。

    1.编写一个service

    // userService.java
    public interface userService {
        public void insertUser();
    }
    
    // xmlImpl.java
    public class xmlImpl implements userService{
        @Override
        public void insertUser() {
            System.out.println("insert a user");
        }
    }

    2.编写Spring核心配置文件,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 id="userService" class="service.xmlImpl"></bean>
    </beans>

    3.使用

    例如写一个servlet文件,在doGet那调用

    public class userView extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 获取Spring容器context
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            
            // 方式1,靠id拿bean
            userService service = (userService) context.getBean("userService");
            service.insertUser();
            
            // 方式2,靠class拿bean
            userService service2 = context.getBean(userService.class);
            service2.insertUser();
            
            response.getWriter().println("123");
        }
    }
  • 相关阅读:
    工具类-vim在shell中卡死的情况
    tomcat日志分类
    逻辑运算
    牛客练习赛29 F 算式子
    牛客练习赛29 B
    查询
    hdu 5984
    zoj 4057
    zoj 4056
    zoj 4054
  • 原文地址:https://www.cnblogs.com/amiezhang/p/9665010.html
Copyright © 2011-2022 走看看