spring的依赖注入 -------基于注解方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jiangwudidebaba/article/details/82918411

前言:

做了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层类似于此

猜你喜欢

转载自blog.csdn.net/jiangwudidebaba/article/details/82918411