java中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里面的
设置类装配的范围:
@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; } }
以上就是关于java中spring依赖注入使用实例详细解析的主要内容了,你都掌握了吗?想要了解更多java实例,敬请关注奇Q工具网。
推荐阅读: