Spring根据XML配置文件注入属性的方法
程序员文章站
2023-12-20 10:38:46
方法一使用setter方法
package com.swift;
public class book {
private string bookname...
方法一使用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 控制反转 springspring根据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包不要缺少
方法二使用有参构造方法
以上这篇spring根据xml配置文件注入属性的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。