一、Spring? Spring興起:2003年,由Rod Johnson創建。總的來說,Spring Framwork從它誕生至今都一直為人所稱道,它的偉大之處自此可見一斑。 核心:IOC&AOP IOC 全稱:Inersion of control-->控制反轉。把對象的創建工作交給框架(有意取 ...
一、Spring?
Spring興起:2003年,由Rod Johnson創建。總的來說,Spring Framwork從它誕生至今都一直為人所稱道,它的偉大之處自此可見一斑。
核心:IOC&AOP
- IOC
全稱:Inersion of control-->控制反轉。把對象的創建工作交給框架(有意取代EJB)。
IOC和DI:兩個概念其實都是闡述同一個內容
- AOP
Aspect Oriented Programming的縮寫,意為:面向切麵編程
二、如何入門(整合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>