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類的對象,并注入String bookName的屬性值
而需要通過配置文件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兩個jar包不要缺少
方法二使用有參構(gòu)造方法
以上這篇Spring根據(jù)XML配置文件注入屬性的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
IntelliJ IDEA中出現(xiàn)"PSI and index do not match"錯誤的解決辦法
今天小編就為大家分享一篇關(guān)于IntelliJ IDEA中出現(xiàn)"PSI and index do not match"錯誤的解決辦法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10
SpringBoot中Formatter和Converter用法和區(qū)別小結(jié)
本文主要介紹了SpringBoot中Formatter和Converter用法和區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
OpenFeign在傳遞參數(shù)為對象類型是為空的問題
這篇文章主要介紹了OpenFeign在傳遞參數(shù)為對象類型是為空的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03

