首页
统计
关于
Search
1
Sealos3.0离线部署K8s集群
1,308 阅读
2
类的加载
864 阅读
3
Spring Cloud OAuth2.0
857 阅读
4
SpringBoot自动装配原理
747 阅读
5
集合不安全问题
646 阅读
笔记
Java
多线程
注解和反射
JVM
JUC
设计模式
Mybatis
Spring
SpringMVC
SpringBoot
MyBatis-Plus
Elastic Search
微服务
Dubbo
Zookeeper
SpringCloud
Nacos
Sentinel
数据库
MySQL
Oracle
PostgreSQL
Redis
MongoDB
工作流
Activiti7
Camunda
消息队列
RabbitMQ
前端
HTML5
CSS
CSS3
JavaScript
jQuery
Vue2
Vue3
Canvas
Linux
容器
Docker
Containerd
Podman
Kubernetes
Python
FastApi
OpenCV
数据分析
牛牛生活
登录
Search
标签搜索
Java
CSS
mysql
RabbitMQ
JavaScript
Redis
OpenCV
JVM
Mybatis-Plus
Camunda
多线程
CSS3
Python
Canvas
Spring Cloud
注解和反射
Activiti
工作流
SpringBoot
ndarray
蘇阿細
累计撰写
452
篇文章
累计收到
4
条评论
首页
栏目
笔记
Java
多线程
注解和反射
JVM
JUC
设计模式
Mybatis
Spring
SpringMVC
SpringBoot
MyBatis-Plus
Elastic Search
微服务
Dubbo
Zookeeper
SpringCloud
Nacos
Sentinel
数据库
MySQL
Oracle
PostgreSQL
Redis
MongoDB
工作流
Activiti7
Camunda
消息队列
RabbitMQ
前端
HTML5
CSS
CSS3
JavaScript
jQuery
Vue2
Vue3
Canvas
Linux
容器
Docker
Containerd
Podman
Kubernetes
Python
FastApi
OpenCV
数据分析
牛牛生活
页面
统计
关于
搜索到
452
篇与
的结果
2020-12-22
Vue基础语法
Vue基础语法1、Vue模板<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue模板</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script> </head> <body> <!--view层 模板--> <div id="app"> </div> <script> var vm = new Vue({ el: '#app', //model:数据 data: { } }); </script> </body> </html>2、else if<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>else if</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script> </head> <body> <!--view层 模板--> <div id="app"> <h1 v-if="type==='A'">A</h1> <h1 v-else-if="type==='B'">B</h1> <h1 v-else>C</h1> </div> <script> var vm = new Vue({ el: '#app', //model:数据 data: { type: 'A' } }); </script> </body> </html>2、for循环<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>for循环</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script> </head> <body> <!--view层 模板--> <div id="app"> <li v-for="(item,index) in items"> {{item.message}}--{{index}} </li> </div> <script> var vm = new Vue({ el: '#app', //model:数据 data: { items:[ {message: '孙笑川'}, {message: '刘波'}, {message: 'Giao哥'} ] } }); </script> </body> </html>4、事件绑定<!DOCTYPE html> <html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>事件绑定</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script> </head> <body> <!--view层 模板--> <div id="app"> <button v-on:click="sayHello">点我</button> </div> <script> var vm = new Vue({ el: '#app', //model:数据 data: { message: "Hello World" }, methods:{ //方法必须定义在Vue的methods对象中,v-on:事件 sayHello: function () { alert(this.message); } } }); </script> </body> </html>5、双向绑定<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>双向绑定</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script> </head> <body> <!--view层 模板--> <div id="app"> 用户名:<input type="text" v-model="msg"> {{msg}} <br> 文本框:<textarea name="text" id="" cols="30" rows="10" v-model="msg1"></textarea>{{msg1}} <br> 性别: <input type="radio" name="sex" value="男" v-model="msg2"> 男 <input type="radio" name="sex" value="女" v-model="msg2"> 女 <span>选中的性别为:{{msg2}}</span> <br> 选择城市: <select v-model="msg3"> <option value="" disabled>--请选择--</option> <option >北京</option> <option>上海</option> <option>广州</option> </select> <span>{{msg3}}</span> </div> <script> var vm = new Vue({ el: '#app', data: { msg: "", msg1: "", msg2: "", msg3: "" } }); </script> </body> </html>6、组件<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>组件</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script> </head> <body> <!--view层 模板--> <div id="app"> <!--组件:传递组件中的值:props--> <!--v-for遍历data中的值,v-bind绑定test01到item,接收遍历出来的值--> <test v-for="item in items" v-bind:test01="item"></test> </div> <script> //定义一个Vue组件component Vue.component("test",{ props: ['test01'], //接收参数 template: '<li>{{test01}}</li>' //模板 } ); var vm = new Vue({ el: '#app', data: { items: ["孙笑川","刘波","Giao哥"] } }); </script> </body> </html>7、vue-axios<!DOCTYPE html> <html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>vue-axios</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <!--v-clock解决闪烁问题--> <style> [v-clock]{ display: none; } </style> </head> <body> <!--view层 模板--> <div id="app" v-clock> <div>{{info.name}}</div> <a v-bind:href="info.url">{{info.url}}</a> <div>{{info.page}}</div> <div>{{info.isNonProfit}}</div> <div>{{info.address.street}}</div> <div>{{info.address.city}}</div> <div>{{info.address.country}}</div> </div> <script> var vm = new Vue({ el: '#app', data(){ return{ //请求的返回参数格式必须和json字符串一样 info:{ name: null, url: null, page: null, isNonProfit: null, address:{ street: null, city: null, country: null }, links:[ { name: null, url: null }, { name: null, url: null }, { name: null, url: null }, ] } } }, mounted(){ //钩子函数 链式编程 axios.get('../data.json').then(response=>(this.info=response.data)); } }); </script> </body> </html>8、计算属性<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算属性</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script> </head> <body> <!--view层 模板--> <div id="app"> <p>currentTime1:{{currentTime1()}}</p> <p>currentTime2:{{currentTime2}}</p> </div> <script> var vm = new Vue({ el: '#app', //model:数据 data: { msg: "Hello" }, methods: { currentTime1: function () { return Date.now(); //返回一个时间戳 } }, computed: { //计算属性,与mothods的方法名不能重名,如果重名,只会调用methods的方法 currentTime2: function () { this.msg; //类似于Mybatis缓存,一旦涉及到增删改,虚拟DOM重新计算 return Date.now(); //虚拟DOM } } }); </script> </body> </html>9、插槽slot<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>slot插槽</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script> </head> <body> <!--view层 模板--> <div id="app"> <todo> <todo-title slot="todo-title" v-bind:title="title"></todo-title> <todo-items slot="todo-items" v-for="item in todoItems" v-bind:item="item"></todo-items> </todo> </div> <script> //slot插槽 Vue.component("todo",{ template: '<div>' + '<slot name="todo-title"></slot>'+ '<ul>' + '<slot name="todo-items"></slot>'+ '</ul>'+ '</div>' }); Vue.component("todo-title",{ props: ['title'], template: '<div>{{title}}</div>' }); Vue.component("todo-items",{ props: ['item'], template: '<li>{{item}}</li>' }); var vm = new Vue({ el: '#app', data: { title: "科目", todoItems: ["Java","PHP","Vue"] } }); </script> </body> </html>10、自定义事件内容分发<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>自定义事件内容分发</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script> </head> <body> <!--view层 模板--> <div id="app"> <todo> <todo-title slot="todo-title" v-bind:title="title"></todo-title> <todo-items slot="todo-items" v-for="(item,index) in todoItems" v-bind:item="item" v-bind:index="index" v-on:remove="removeItems(index)"></todo-items> </todo> </div> <script> //slot插槽 Vue.component("todo",{ template: '<div>' + '<slot name="todo-title"></slot>'+ '<ul>' + '<slot name="todo-items"></slot>'+ '</ul>'+ '</div>' }); Vue.component("todo-title",{ props: ['title'], template: '<div>{{title}}</div>' }); Vue.component("todo-items",{ props: ['item','index'], //只能绑定当前组件的方法 template: '<li>{{index}}--{{item}} <button @click="remove">删除</button></li>', methods: { remove: function (index) { //自定义事件分发 this.$emit('remove',index); } } }); var vm = new Vue({ el: '#app', data: { title: "科目", todoItems: ["Java","PHP","Vue"] }, methods: { removeItems: function (index) { console.log("删除"+this.todoItems[index]+"成功!"); this.todoItems.splice(index,1); //一次删除一个元素 } } }); </script> </body> </html>
2020年12月22日
71 阅读
0 评论
0 点赞
2020-12-17
JSON
JSONJSON(JavaScript Object Notation,JS标记对象)是一种轻量级的数据交换格式。1、jackson导入依赖<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.0</version> </dependency>Utils工具类package com.sw.utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.text.SimpleDateFormat; /** * @Author suaxi * @Date 2020/12/17 16:08 */ public class JsonUtils { public static String getJson(Object object){ return getJson(object,"yyyy-MM-dd HH:mm:ss"); } public static String getJson(Object object,String dateFormate){ ObjectMapper mapper = new ObjectMapper(); //不使用时间戳 mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false); //自定义时间格式 SimpleDateFormat sdf = new SimpleDateFormat(dateFormate); mapper.setDateFormat(sdf); try { return mapper.writeValueAsString(object); } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } } Controllerpackage com.sw.controller; import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.sw.pojo.User; import com.sw.utils.JsonUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @Author suaxi * @Date 2020/12/17 15:38 */ //@Controller @RestController public class UserController { @RequestMapping("/j1") //@ResponseBody //不会走视图解析器,直接返回一个字符串 public String test01() throws JsonProcessingException { //jackson ObjectMapper ObjectMapper mapper = new ObjectMapper(); User user = new User("孙笑川", 33, "男"); String s = mapper.writeValueAsString(user); return s; } @RequestMapping("/j2") public String test02() throws JsonProcessingException { List<User> userList = new ArrayList<User>(); User user1 = new User("孙笑川1", 33, "男"); User user2 = new User("孙笑川2", 33, "男"); User user3 = new User("孙笑川3", 33, "男"); userList.add(user1); userList.add(user3); userList.add(user2); return JsonUtils.getJson(userList); } @RequestMapping("/j3") public String test03() throws JsonProcessingException { return JsonUtils.getJson(new Date()); } } 2、fastjson<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.75</version> </dependency>Controllerpackage com.sw.controller; import com.alibaba.fastjson.JSON; import com.sw.pojo.User; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; /** * @Author suaxi * @Date 2020/12/17 15:38 */ //@Controller @RestController public class UserController { @RequestMapping("/j4") public String test04(){ List<User> userList = new ArrayList<User>(); User user1 = new User("孙笑川1", 33, "男"); User user2 = new User("孙笑川2", 33, "男"); User user3 = new User("孙笑川3", 33, "男"); userList.add(user1); userList.add(user3); userList.add(user2); String s = JSON.toJSONString(userList); return s; } }
2020年12月17日
128 阅读
0 评论
0 点赞
2020-12-17
RestFul风格
RestFul风格RestFul就是一个资源定位及资源操作的风格,它不是标准也不是协议,基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。传统资源操作方式:http://127.0.0.1/project/findUser.do?id=1 查询 GEThttp://127.0.0.1/project/addUser.do 新增 POSThttp://127.0.0.1/project/modifyUser.do 更新 POSThttp://127.0.0.1/project/deleteUser.do?id=1 删除 GET或POST使用RestFul风格:http://127.0.0.1/project/1 查询 GEThttp://127.0.0.1/project 新增 POSThttp://127.0.0.1/project 更新 POSThttp://127.0.0.1/project/1 删除 GET或POST常用的资源操作:POST、DELETE、PUT、GETpackage com.sw.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * @Author suaxi * @Date 2020/12/17 11:25 */ @Controller public class RestFulController { //传统风格 http://localhost:8088/add01?a=1&b=1 @RequestMapping(value = "/add01/{a}/{b}",method = RequestMethod.GET) public String test01(@PathVariable int a,@PathVariable int b, Model m){ int result = a + b; m.addAttribute("msg","结果1为:"+result); return "hello"; } //简化 http://localhost:8088/add02/1/2 @PostMapping("/add02/{a}/{b}") public String test02(@PathVariable int a,@PathVariable int b, Model m){ int result = a + b; m.addAttribute("msg","结果2为:"+result); return "hello"; } } 注:@PathVariable 让方法参数的值对应绑定到一个URI模板变量上
2020年12月17日
97 阅读
0 评论
0 点赞
2020-12-17
SpringMVC执行原理
SpringMVC执行原理流程分析:DispatcherServlet表示前置控制器,是整个SpringMVC的控制中心。用户发出请求,DispatcherServlet接收并拦截请求HandlerMapping为处理器映射,DispatcherServlet调用HandlerMapping,根据请求url查找HandlerHandlerExecution为具体的Handler,其作用是根据url查找控制器HandlerExecution将解析后的信息传递给DispatcherServletHandlerAdapter表示处理适配器,按照特定的规则去执行HandlerHandler让具体的Controller执行Controller将具体的执行信息返回给HandlerAdapter(ModelAndView)HandlerAdapter将视图逻辑名或模型传递给DispatcherServletDispatcherServlet调用视图解析器(ViewResolver)解析HandlerAdapter传递的逻辑视图名视图解析器将解析的逻辑视图名传给DispatcherServletDispatcherServlet根据视图解析器解析的结果,调用具体的视图返回用户请求,呈现视图给用户
2020年12月17日
89 阅读
0 评论
0 点赞
2020-12-16
AOP
AOPAOP(Aspect Oriented Programing),面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,利用AOP可以对业务逻辑的各个部分进行隔离,从而使业务逻辑各部分之间的耦合降低,提高程序的可重用性。1、Aop在Spring中的作用==提供声明式事务;允许用户自定义切面==横切关注点:跨越应用程序多个模块的方法或功能,即:与业务逻辑无关,但需要关注的部分就是横切关注点,如:日志、缓存、事务等切面(Aspect):横切关注点被模块化的都特殊对象,具体为一个类通知(Advice):切面必须要完成的工作,类中的一个方法目标(Target):被通知对象代理(Proxy):向目标对象应用通知之后创建的对象切入点(PointCut):需要执行切面通知的”地点“连接点(JoinPoint):与切入点匹配的执行点在SpringAop中,通过Advice定义横切逻辑,Spring中支持5中类型的Advice:通知类型连接点实现接口前置通知方法前org.springframework.aop.MethodBeforeAdvice后置通知方法后org.springframework.aop.AfterReturningAdvice环绕通知方法前后org.springframework.aop.MethodInterceptor异常抛出通知方法抛出异常org.springframework.aop.ThrowsAdvice引介通知类中增加新的方法属性org.springframework.aop.IntroductionInterceptor2、使用Spring实现AOP在pom.xml中导入依赖<dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> </dependencies>3、使用Spring实现Aop方式一:使用Spring的API接口方式二:自定义实现AOP【定义切面】方式三:使用注解<?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--注册bean--> <bean id="userService" class="com.sw.service.UserServiceImpl"/> <bean id="log" class="com.sw.log.Log"/> <bean id="afterLog" class="com.sw.log.AfterLog"/> <!--方式一:使用原生Spring API配置--> <!--配置aop:需导入AOP约束--> <aop:config> <!--切入点:execution(要执行的位置)--> <aop:pointcut id="pointcut" expression="execution(* com.sw.service.UserServiceImpl.*(..))"/> <!--执行环绕增强--> <aop:advisor advice-ref="log" pointcut-ref="pointcut"/> <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/> </aop:config> <!--方式二:自定义--> <bean id="diy" class="com.sw.diy.DiyLog"/> <aop:config> <!--自定义切面,ref:要引用的类--> <aop:aspect ref="diy"> <!--切入点--> <aop:pointcut id="pointcut" expression="execution(* com.sw.service.UserServiceImpl.*(..))"/> <!--通知--> <aop:before method="before" pointcut-ref="pointcut"/> <aop:after method="after" pointcut-ref="pointcut"/> </aop:aspect> </aop:config> <!--方式三:通过注解--> <bean id="annotationPointCut" class="com.sw.diy.AnnotationPointCut"/> <!--开启注解 JDK:expose-proxy="false"(默认) cglib:expose-proxy="true" --> <aop:aspectj-autoproxy /> </beans>
2020年12月16日
207 阅读
0 评论
0 点赞
2020-12-16
代理模式
代理模式代理模式的分类:静态代理动态代理自己 --- > 租房中介 --- > 房东1、静态代理角色分析:抽象角色:一般使用抽象类或接口真实角色:被代理的角色代理角色:代理真实角色,同时可以做一些附属操作客户:访问代理对象的人租房Demo:1、接口package com.sw.demo01; /** * @Author suaxi * @Date 2020/12/16 10:06 */ //租房 public interface Rent { public void rent(); } 2、真实角色package com.sw.demo01; /** * @Author suaxi * @Date 2020/12/16 10:08 */ //房东 public class Host implements Rent{ public void rent() { System.out.println("房东要出租房子"); } } 3、代理角色package com.sw.demo01; /** * @Author suaxi * @Date 2020/12/16 10:10 */ public class Proxy { private Host host; public Proxy() { } public Proxy(Host host) { this.host = host; } public void rent(){ seeHouse(); host.rent(); hetong(); getFee(); } //看房 public void seeHouse(){ System.out.println("中介带租客看房!"); } //签合同 public void hetong(){ System.out.println("签租赁合同"); } //收中介费 public void getFee(){ System.out.println("中介收取中介费用!"); } } 4、客户端访问代理角色package com.sw.demo01; /** * @Author suaxi * @Date 2020/12/16 10:09 */ public class Client { public static void main(String[] args) { //房东想要出租房子 Host host = new Host(); //通过中介帮房东代理发布出租信息,同时中介角色带有一些附属操作 Proxy proxy = new Proxy(host); //客户不用面对房东,直接找中介即可 proxy.rent(); } } 静态代理的优点:可以使真实角色(房东)的操作更加纯粹,即只做租房一件事,不用去关注其他的公共事务公共事务交给代理角色(中介),实现业务分工公共业务需要拓展的时候,方便集中管理缺点:一个真实角色就需要对应的一个代理角色,开发效率低。2、动态代理动态代理与静态代理的角色一样代理类是动态生成的分为两类:基于接口的动态代理,基于类的动态代理基于接口:JDK动态代理基于类:cglibJava字节码实现:javasist动态代理的优点:可以使真实角色的操作更加纯粹,不用去关注其他的公共事务公共事务交给代理角色,实现业务分工公共业务需要拓展的时候,方便集中管理一个动态代理类代理的是一个接口,即对应一类业务一个动态代理可以代理多个类,只要实现同一个接口即可1、接口package com.sw.demo04; /** * @Author suaxi * @Date 2020/12/16 11:00 */ public interface UserService { public void add(); public void delete(); public void find(); public void update(); } 2、真实角色package com.sw.demo04; /** * @Author suaxi * @Date 2020/12/16 11:01 */ public class UserServiceImpl implements UserService{ public void add() { System.out.println("新增了一个用户"); } public void delete() { System.out.println("删除了一个用户"); } public void find() { System.out.println("查询用户"); } public void update() { System.out.println("修改用户信息"); } } 3、ProxyInvocationHandlerpackage com.sw.demo04; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * @Author suaxi * @Date 2020/12/16 10:39 */ public class ProxyInvocationHandler implements InvocationHandler { //被代理的接口 private Object target; public void setTarget(Object target) { this.target = target; } //生成代理对象 public Object getProxy(){ return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this); } //处理代理实例,并返回结果 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { log(method.getName()); Object result = method.invoke(target, args); return result; } public void log(String msg){ System.out.println("执行了"+msg+"方法!"); } } 4、具体实现package com.sw.demo04; /** * @Author suaxi * @Date 2020/12/16 10:57 */ public class Client { public static void main(String[] args) { //真实角色 UserServiceImpl userService = new UserServiceImpl(); //代理角色(不存在) ProxyInvocationHandler pih = new ProxyInvocationHandler(); pih.setTarget(userService); //设置要代理的对象 //动态生成代理类 UserService proxy = (UserService) pih.getProxy(); proxy.add(); } } 代理多个类时,只要实现同一个UserService接口即可UserServiceImpl01 userService = new UserServiceImpl01(); UserServiceImpl02 userService = new UserServiceImpl02(); ……
2020年12月16日
119 阅读
0 评论
0 点赞
2020-12-16
Bean的自动装配
Bean的自动装配==Spring会在上下文中自动寻找,并自动给bean装配属性==三种方式:1、在xml中显示的配置2、在Java中显示配置3、隐式的自动装配bean1、测试环境搭建:一个人有两个宠物Demo2、byName自动装配<bean id="cat" class="com.sw.pojo.Cat"/> <bean id="dog" class="com.sw.pojo.Dog"/> <!--byName:会自动在容器上下文中查找和自己对象中(Person)set方法后面的值对应的beanid--> <bean id="person" class="com.sw.pojo.Person" autowire="byName"> <property name="name" value="孙笑川"/> </bean>3、byType自动装配<bean id="cat2" class="com.sw.pojo.Cat"/> <bean id="dog1" class="com.sw.pojo.Dog"/> <!-- byName:会自动在容器上下文中查找,和自己对象中(Person)set方法后面的值对应的beanid byType:会自动在容器上下文中查找,和自己对象属性类型相对应的bean --> <bean id="person" class="com.sw.pojo.Person" autowire="byType"> <property name="name" value="孙笑川"/> </bean>注:byName:需要保证所有bean的id唯一,且这个bean需要和自动注入的属性的set方法的值一致byType:需要保证所有bean的class唯一,且这个bean需要和自动注入的属性的类型一致4、使用注解实现自动装配1、导入context约束2、开启注解<?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> </beans>@Autowired 直接在属性上用即可,也可以在set方法上使用@Nullable //字段标记了这个注解,说明这个字段可以为null@Autowired(required = false) //如果显示的定义Autowired的required属性为fasle,说明这个对象可以为空//默认为true 不允许为空 public @interface Autowired { boolean required() default true; }注:如果@Autowired自动装配的环境比较复杂,无法通过一个@Autowired注解完成的时候,可以使用@Qualifier(value = "xxx"),指定一个唯一的bean对象public class Person { private String name; @Autowired private Dog dog; @Autowired @Qualifier(value = "cat") private Cat cat; }@Resourcepublic class Person { private String name; @Resource(name = "cat1212") private Dog dog; @Resource private Cat cat; }小结:@Autowired与@Resource的区别都是用来自动装配的@Autowired 通过byType的方式实现,且对象必须存在@Resource 默认通过byName的方式实现,如果找不到对应的bean id,则通过byType实现
2020年12月16日
144 阅读
0 评论
0 点赞
2020-12-15
依赖注入
依赖注入1、构造器注入参考IoC创建对象的方式2、Set方式注入依赖注入:Set注入依赖:bean对象的创建依赖于容器注入:bean对象中的所有属性,由容器来注入环境搭建:1、复杂类型package com.sw.pojo; /** * @Author suaxi * @Date 2020/12/14 16:32 */ public class Adress { private String adress; public String getAdress() { return adress; } public void setAdress(String adress) { this.adress = adress; } } 2、真实测试对象package com.sw.pojo; import java.util.*; /** * @Author suaxi * @Date 2020/12/14 16:32 */ public class Student { private String name; private Adress adress; private String[] books; private List<String> hobbys; private Map<String,String> card; private Set<String> games; private String wife; private Properties info; …… } 3、beans.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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="student" class="com.sw.pojo.Student"> <!--普通值注入 value--> <property name="name" value="孙笑川"/> </bean> </beans>4、测试类import com.sw.pojo.Student; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @Author suaxi * @Date 2020/12/14 16:38 */ public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Student student = (Student) context.getBean("student"); System.out.println(student.getName()); } } beans.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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="address" class="com.sw.pojo.Address"> <property name="address" value="昆明"/> </bean> <bean id="student" class="com.sw.pojo.Student"> <!--普通值注入 value--> <property name="name" value="孙笑川"/> <!--bean注入 ref--> <property name="address" ref="address"/> <!--数组--> <property name="books"> <array> <value>高数一</value> <value>英语一</value> <value>毛概</value> </array> </property> <!--list--> <property name="hobbys"> <list> <value>跑步</value> <value>游泳</value> <value>听音乐</value> </list> </property> <!--map--> <property name="card"> <map> <entry key="身份证" value="12345678"/> <entry key="银行卡" value="87654321"/> </map> </property> <!--set--> <property name="games"> <set> <value>LOL</value> <value>FF14</value> <value>CSGO</value> </set> </property> <!--null--> <property name="wife"> <null/> </property> <!--properties--> <property name="info"> <props> <prop key="姓名">孙笑川</prop> <prop key="学号">123</prop> <prop key="性别">男</prop> </props> </property> </bean> </beans>3、拓展方式注入可以使用p命名空间和c命名空间<?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:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--p命名空间注入,可以直接注入属性的值:property--> <bean id="user" class="com.sw.pojo.User" p:id="1" p:name="孙笑川"/> <!--c命名空间注入,通过构造器注入constructor-args--> <bean id="user1" class="com.sw.pojo.User" c:id="2" c:name="刘波"/> </beans>注:使用前需导入xml约束xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"4、bean的作用域1、单例模式(Spring默认)<bean id="user1" class="com.sw.pojo.User" c:id="2" c:name="刘波" scope="singleton"/>@Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml"); User user1 = (User) context.getBean("user"); User user2 = (User) context.getBean("user"); System.out.println(user1==user2); //true }2、原型模式:每次从容器中get的时候都会产生一个新对象<bean id="user1" class="com.sw.pojo.User" c:id="2" c:name="刘波" scope="prototype"/>@Test public void test1(){ ApplicationContext context = new ClassPathXmlApplicationContext("userBeans.xml"); User user1 = (User) context.getBean("user1"); User user2 = (User) context.getBean("user1"); System.out.println(user1.hashCode()); //838411509 System.out.println(user2.hashCode()); //1434041222 System.out.println(user1==user2); //false }3、其余的request、session、application在web开发中使用
2020年12月15日
100 阅读
0 评论
0 点赞
1
...
42
43
44
...
57