1. 程式人生 > >Spring框架context的註解管理方法之二 使用註解註入對象屬性

Spring框架context的註解管理方法之二 使用註解註入對象屬性

.org es2017 swift package 自動 clas 找到 裝配 alt

首先還是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;

這種方法使用較多

Spring框架context的註解管理方法之二 使用註解註入對象屬性