Spring根據(jù)XML配置文件注入屬性的方法
方法一使用setter方法
package com.swift; public class Book { private String bookName; public void setBook(String bookName) { this.bookName = bookName; } @Override public String toString() { return "Book [book=" + bookName + "]"; } }
在Spring框架中,假定Servlet類中不能直接生成Book類的對(duì)象,并注入String bookName的屬性值
而需要通過(guò)配置文件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"> <!-- IoC 控制反轉(zhuǎn) SpringSpring根據(jù)XML配置文件注入屬性 --> <bean id="book" class="com.swift.Book"> <property name="bookName" value="三體——黑暗森林"></property> </bean> </beans>
Servlet類代碼:
package com.swift; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; @WebServlet("/book") public class BookServlet extends HttpServlet { private static final long serialVersionUID = 1L; public BookServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); response.getWriter().append("Served at: ").append(request.getContextPath()); @SuppressWarnings("resource") //就是下邊這幾句了 ApplicationContext context=new ClassPathXmlApplicationContext("a.xml"); Book book=(Book) context.getBean("book"); String bookInfo=book.fun(); response.getWriter().println(); response.getWriter().append(bookInfo); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
注意
beans 、context、core 和expression核心jar包
以及commons-logging 和log4j兩個(gè)jar包不要缺少
方法二使用有參構(gòu)造方法
以上這篇Spring根據(jù)XML配置文件注入屬性的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
IntelliJ IDEA中出現(xiàn)"PSI and index do not match"錯(cuò)誤的解決辦法
今天小編就為大家分享一篇關(guān)于IntelliJ IDEA中出現(xiàn)"PSI and index do not match"錯(cuò)誤的解決辦法,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10SpringBoot中Formatter和Converter用法和區(qū)別小結(jié)
本文主要介紹了SpringBoot中Formatter和Converter用法和區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07JAVA多種方法實(shí)現(xiàn)字符串反轉(zhuǎn)
大家好,本篇文章主要講的是JAVA多種方法實(shí)現(xiàn)字符串反轉(zhuǎn),感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽2022-01-01OpenFeign在傳遞參數(shù)為對(duì)象類型是為空的問(wèn)題
這篇文章主要介紹了OpenFeign在傳遞參數(shù)為對(duì)象類型是為空的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03