首先还是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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启注解扫描 --> <context:component-scan base-package="com.swift"></context:component-scan> </beans>
接着是假定dao的类
package com.swift; import org.springframework.stereotype.Component; @Component(value="dao") public class Dao { public String fun() { return "This is Dao's fun()........"; } }
生成一个对象很方便,甚至@Component(value="dao")中的value=都可以不写,变成
@Component("dao")
然后是假定service的类
package com.swift; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component(value="service") public class Service { @Autowired private Dao dao; public String fun() { return "This is Service's fun()......."+"\r\n"+this.dao.fun(); } //注意使用注解方法,不需要自己生成setter方法了 public void setDao(Dao dao) { this.dao = dao; } }
与配置文件中使用<bean id="service" class="com.swift.Service"><property name="dao" ref="dao"></property></bean>
不同,注解生成两个对象后,再注解属性
@Autowired
就搞定了,自动装配,自动连线
最后使用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("/test") public class ServletTest extends HttpServlet { private static final long serialVersionUID = 1L; public ServletTest() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); ApplicationContext context=new ClassPathXmlApplicationContext("zhujie.xml"); Service service=(Service) context.getBean("service"); String test=service.fun(); response.getWriter().append(test); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
浏览器结果如下
自动装载的这种方法 @Autowired 原理是通过类名找到定义的对象,这种注解使用不多,因为多个对象存在的话,注入的是哪个?
所以,使用
另一个注解,可以明确到底注入哪个对象
@Resource(name="dao")
private Dao dao;
这种方法使用较多