1. 程式人生 > >spring的依賴注入 -------基於註解方式

spring的依賴注入 -------基於註解方式

前言:

做了2年的軟體,剛開始入行的時候,沒有個目標基本上都是在摸索,技術看的我眼花繚亂,這個想學,那個也想學結果是對很多技術一知半解的,工作中才發現,我們要掌握的一門可以搞定快速開發搞定所有業務需求的技術, 所以現在我要對spring的東西達到一個深層次的掌握,儘量避免百度,在開發中避免查詢查詢api提高開發速度,在前端方面我覺得知道掌握jquery,easyui相關的技術即可,在前端方面不追求廣度,只追求技術的深度

spring依賴注入

spring的依賴注入指的是應用程式本身不負責物件的建立和維護,應用程式所需要的類在應用載入啟動的時候建立完成,並通過set方法將類直接載入到應用程式中(DI),在spring容器中並設定類的一系類屬性,例如的類的作用域,bean與bean之間的關係,類的模式,在spring容器中檢測,類的生命週期等

現在spring使用方式有基於註解和基於xml的2中方式:
先介紹註解的方式:
例項化的註解列表:
@compoent :應用於普通的類中
@service:在servie層中使用
@controller:標記controller層
@reposistory:在dao層中使用
@resource:根據設定的明朝名稱來進行注入

注入的註解的標籤:
@autowired:自動注入的方式進行注入,預設根據類的名稱來進行裝配
@Resource(name="")沒有name時3和autowired一樣但是他可以根據名稱進行裝配

裝配標籤:在xml裡面的
<context:compoent-scan pack-name="">

設定類裝配的範圍:

@Scope()
在這裡插入圖片描述

使用例項:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
     
     <mvc:annotation-driven /> 
     <!-- 掃描controller(controller層注入) -->
     <!-- 當類上面有 @Compoent, @service, @Controller,@repository 
    	 也可以定義為 1 <context:component-scan base-package="cn.gacl.dao.impl,cn.gacl.service.impl,cn.gacl.action"/>
     
     	@Component
		是所有受Spring 管理元件的通用形式,@Component註解可以放在類的頭上,@Component不推薦使用。
		@Controller
		@Controller對應表現層的Bean,也就是Action
		@Scope("prototype") 用於生命bean的範圍
		
     -->
     <!-- 開始掃 @Compoent, @service, @Controller,@repository 並 相關的標籤 將這些類例項化
     	相當於在 <bean id="" class=""></bean>
     -->
     <context:component-scan base-package="com.mvc" />
     <!-- springMVC上傳檔案時,需要配置MultipartResolver處理器 -->
    <bean id="multipartResolver" 
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <property name="maxUploadSize" value="10485760000"></property>
        <property name="maxInMemorySize" value="40960"></property>
    </bean>
     <!-- 對模型檢視新增前後綴 -->
     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/" p:suffix=".jsp"/>
      
</beans>

在檔案載入檔案的使用將類自動注入

controller層樣例:

package com.mvc.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fileupload.dao.ContextDao;
import com.fileupload.dao.impl.ContextDaoImpl;
import com.mvc.model.OAArchiveCjRTypeArchives;
import com.mvc.model.OAArchiveCjRTypeFile;
import com.mvc.model.OArchiveCjRtypeProject;
import com.mvc.model.User;
import com.mvc.service.UserService;



@Controller
@Scope
public class UserController {
	
	private static Logger logger = Logger.getLogger(UserController.class); 
	
	@Autowired
	private UserService service;
	
	private List list;
	
	private Map map;
	
	
	List<User> user;
	
    @RequestMapping("/")    
    public ModelAndView getIndex(){     
    	// 記錄debug級別的資訊    
	    logger.debug("This is debug message.");    
	    // 記錄info級別的資訊    
	    logger.info("This is info message.");    
	    // 記錄error級別的資訊    
	    logger.error("This is error message.");   
	    
        ModelAndView mav = new ModelAndView("index");   
        return mav;    
    }   
    
    
    
    @RequestMapping(value = "/mvctest", method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @ResponseBody()
    public Map<String,Object> mvctest(@RequestParam("name") String name){
    	
    	
    	logger.info(name);
    	List<String> list = new ArrayList<String>();
    	
    	list.add("tomcat");
    	list.add("eclipse");
    	
    	
    	Map<String,Object> map = new HashMap<String,Object>();
    	
    	map.put("list", list);
    	
    	
    	return map;
    	
    }
    
    @RequestMapping(value="/listUser", method=RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @ResponseBody()
    public List<User> listUser(){
    	
    	List<User> list = service.listUser();
    	
    	
    	return list;
    }
    

    
 /*   @RequestMapping(value="/listTest", method=RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @ResponseBody()
    public List listTest(){
    	
    	List list = this.list;
    	
    	return list;
    	
    }*/
    
    /*
     * 包裝型別的資料,在傳引數的時候不會報錯報0 int和integer
     * */
    
    @RequestMapping(value="/integerTest", method=RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @ResponseBody()
    public Integer IntegerTest(@RequestParam("num")Integer num){
		return num;
    }
    //傳陣列
    
    @RequestMapping(value="/arrayTest", method=RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @ResponseBody()
    public String arrayTest(@RequestParam("name")String[] name){
    	
    	StringBuffer buf = new StringBuffer();
    	
    	for(String nameVal:name){
    		buf.append(nameVal).append("   ");
    	}
        	
		return buf.toString();
    }
    //http://localhost:8080/mvctest/objectTest?userName=jiang&userTel=123456
    @RequestMapping(value="/objectTest", method=RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @ResponseBody()
    public String objectTest(OArchiveCjRtypeProject rp){
    	
    	return rp.toString();
    }
    
    
    //
    @RequestMapping(value="/listTest", method=RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @ResponseBody()
    public String listTest(List<User> user){
    	
    	return user.toString();
    }
    
    
    //modelAndView test
    
    @RequestMapping(value="/viewTest", method=RequestMethod.GET)
    public ModelAndView viewTest(){
    	ModelAndView model = new ModelAndView("index");
    	model.addObject("name", "jiang");
    	model.getModel().put("age","1112");
    	return model;
    }
    
    @InitBinder("user")
    public void userBind( WebDataBinder bind){
    	
    	bind.setFieldDefaultPrefix("user.");
    };
    
    @InitBinder("admin")
    public void adminBind( WebDataBinder bind){
    	
    	bind.setFieldDefaultPrefix("admin.");
    };
    
	public List getList() {
		return list;
	}


	public void setList(List list) {
		this.list = list;
	}



	public Map getMap() {
		return map;
	}



	public void setMap(Map map) {
		this.map = map;
	}



	public List<User> getUser() {
		return user;
	}



	public void setUser(List<User> user) {
		this.user = user;
	}
    
	
}

service層和到dao層類似於此