当前位置: 移动技术网 > IT编程>开发语言>Java > 一文助您成为Java.Net双平台高手

一文助您成为Java.Net双平台高手

2019年02月16日  | 移动技术网IT编程  | 我要评论
写在前面:本文乃标题党,不是月经贴,侧重于Web开发差异,或细节或概述,若有不对之处,还请各位读者本着友好互助的心态批评指正。由于博客园中.Neter较多(个人感觉),因此本文也可以作为.Neter到Java开发的快速入门。 总述 在.Net开发中,微软官方框架类可以很好的解决的大部分问题,开发人员 ...

写在前面:本文乃标题党,不是月经贴,侧重于web开发差异,或细节或概述,若有不对之处,还请各位读者本着友好互助的心态批评指正。由于博客园中.neter较多(个人感觉),因此本文也可以作为.neter到java开发的快速入门。


总述

在.net开发中,微软官方框架类可以很好的解决的大部分问题,开发人员可以心安理得的在一亩三分地腾挪躲闪出花来;偶有一些优(zhao)秀(chao)的开源库,各库的关注点也基本不会重样;所以.neter只要按部就班即可。而java喜欢定义各种规范,各路大神各自实现,因此一个概念常常会有很多的第三方库,虽然有spring这种杀手级框架,不过基于ioc和aop的设定,spring家族也变得异常庞大,在编码时需要引入大量的annotation来织入逻辑;虽然貌似最大程度的解耦了各组件,但导致代码的可读性和可调试性非常不好,碎片化非常严重。不过也因为如此,java社区成为设计思想的孕育地,并常常出现一些让人击节的设计模式。其中的概念传播到隔壁.net圈,圈内小白往往一脸懵逼,而少数大佬不管不顾拿来套用,往往是用错了,或者让人不知所以。

笼统来说,.net框架隐藏细节,简便清晰,套路单一,但常陷入知其然不知其所以然的懵逼境地;java&spring注解隐藏细节,概念繁多,没有方向感或有被绕晕的风险,但一旦破位而出,则纵横捭阖天地之大可任意施展至其它平台。不过两者差异随着.net的开源以肉眼不可见的速度缓慢消失,特别是最近几年,.net在语法层面已经超越了java良多,java虽然一时半会抹不开面子,但也一直在改进。到的本文撰写时分,借用不知名网友语:“c#语法已经达到java20,用户量撑死java7,生态java1.4”。

两者竞争主要集中在web开发领域。目前在该领域,spring boot已基本成为事实上java平台的“官方框架”,我想大部分开发人员并不会在意背后的实现细节,从这个方面来讲,两个平台的开发模式有一定程度的相似。


数据持久层

为啥这节标题不是orm呢?毕竟orm现在是业界标准,很难想象这个时代还需要手写sql,还需要手动操作jdbc/ado;如果你打算这么干,一定会被年轻一辈打心眼里鄙视:)

java

orm:十多年前,hibernate就开始兴起,它提供了半对象化的hql和完全的面向对象qbc。之后也出现了其它一些orm比如toplink。

jpa:jdk5引入,是sun公司为了统一目前众多orm而提出的orm规范(又犯了定义规范的瘾)。这个规范出来后,很多orm表示支持,但以前的还得维护啊,所以像hibernate就另外建了一个分支叫hibernate jpa。网友所言:“jpa的出现只是用于规范现有的orm技术,它不能取代现有的hibernate等orm框架,相反,采用jpa开发时,我们仍将使用这些orm框架,只是此时开发出来的应用不在依赖于某个持久化提供商。应用可以在不修改代码的情况下载任何jpa环境下运行,真正做到低耦合,可扩展的程序设计。类似于jdbc,在jdbc出现以前,我们的程序针对特性的数据库api进行编程,但是现在我们只需要针对jdbc api编程,这样能够在不改变代码的情况下就能换成其他的数据库。”

spring data jpa:有了jpa,我们就可以不在意使用哪个orm了,但是spring data jpa更进一步(为spring家族添砖加瓦),按约定的方式自动给我们生成持久化代码,当然它底层还是要依赖各路orm的。相关资料:使用 spring data jpa 简化 jpa 开发

mybatis:随着时间的流逝,hibernate曾经带来的荣耀已经被臃肿丑陋的配置文件,无法优化的查询语句淹没。很多人开始怀念可一手掌控数据操作的时代,于是mybatis出现了。mybatis不是一个完整的orm,它只完成了数据库返回结果到对象的映射,而存取逻辑仍为sql,写在mapper文件中,它提供的语法在一定程度上简化了sql的编写,最后mybatis将sql逻辑映射到接口方法上(在mapper文件中指定<mapper namespace="xxx">,其中xxx为映射的dao接口)。针对每个表写通用增删改查的mapper sql既枯燥又易出错,所以出现了mybatis-generator之类的代码生成工具,它能基于数据表生成实体类、基本crud的mapper文件、对应的daointerface。

:在mybatis的基础上,提供了诸如分页、复杂条件查询等功能,基础crud操作不需要额外写sql mapper了,只要dao接口继承basemapper接口即可。当然为了方便,它也提供了自己的代码生成器。

.net

  orm:主流entity framework,除开orm功能外,它还提供了code first、db first、t4代码生成等特性。性能上与hibernate一个等级,但使用便捷性和功能全面性较好,更别说还有linq的加持。


认证&授权&鉴权

认证是检测用户/请求是否合法,授权是赋予合法用户相应权限,鉴权是鉴别用户是否有请求某项资源的权限(认证和授权一般是同时完成)。我们以web为例。

c#/asp.net mvc

提供了两个filter:iauthenticationfilter 和 authorizeattribute,前者用于认证授权,后者用于鉴权。

 1 //iauthenticationfilter 认证,认证是否合法用户
 2 public class adminauthenticationfilter : actionfilterattribute, iauthenticationfilter
 3 {
 4     public void onauthentication(authenticationcontext filtercontext)
 5     {
 6         iprincipal user = filtercontext.principal;
 7         if (user == null || !user.identity.isauthenticated)
 8         {
 9             httpcookie authcookie = filtercontext.httpcontext.request.cookies[formsauthentication.formscookiename];
10             if (authcookie != null)
11             {
12                 formsauthenticationticket ticket = formsauthentication.decrypt(authcookie.value);
13                 if (ticket != null && !string.isnullorempty(ticket.userdata))
14                 {
15                     var userid = convert.toint32(ticket.userdata);
16                     user = enginecontext.resolve<pfmanagerservice>().getmanager(userid);
17                     filtercontext.principal = user; //后续会传递给httpcontext.current.user
18                 }
19             }
20         }
21     }
22 
23     public void onauthenticationchallenge(authenticationchallengecontext filtercontext)
24     {
25         // 认证失败执行
26     }
27 }
view code

认证成功后,将user赋给filtercontext.principal(第17行),filtercontext.principal接收一个iprincipal接口对象,该接口有个 bool isinrole(string role) 方法,用于后续的鉴权过程。

 1 public class adminauthorizationfilter : authorizeattribute
 2 {        
 3     public override void onauthorization(authorizationcontext filtercontext)
 4     {
 5         //childaction不用授权
 6         if (filtercontext.ischildaction)
 7             return;
 8 
 9         if (!filtercontext.actiondescriptor.isdefined(typeof(allowanonymousattribute), true) && !filtercontext.actiondescriptor.controllerdescriptor.isdefined(typeof(allowanonymousattribute), true))
10         {           
11             if (filtercontext.httpcontext.user != null && filtercontext.httpcontext.user.identity.isauthenticated)
12             {
13                 var controllername = filtercontext.routedata.values["controller"].tostring().tolower();
14                 var actionname = filtercontext.routedata.values["action"].tostring().tolower();
15                 //只要登录,则都能访问工作台
16                 if (controllername.tolower() == "home" && actionname.tolower() == "index")
17                     this.roles = string.empty;
18                 else
19                 {
20                     var roleids = enginecontext.resolve<bemoduleservice>().getroleidshasmoduleauthorization(controllername, actionname, masonplatformtype.adminplatform);
21                     if (roleids == null)
22                     {
23                         filtercontext.result = new httpnotfoundresult();
24                         return;
25                     }
26                     //将资源所需权限赋给成员变量roles
27                     this.roles = string.join(",", roleids);
28                 }
29             }
30         }
31 
32         base.onauthorization(filtercontext);
33     }
34 }
view code

注意第27行,我们将拥有该资源的所有权限赋给roles,之后authorizeattribute会循环roles,依次调用当前用户(上述的filtercontext.principal)的isinrole方法,若其中一个返回true则表明用户有访问当前资源的权限。

java/spring security

也提供了两个类,一个filter和一个interceptor:authenticationprocessingfilter用于用户认证授权,abstractsecurityinterceptor用于鉴权。spring security基于它们又封装了几个类,主要几个:websecurityconfigureradapter、filterinvocationsecuritymetadatasource、accessdecisionmanager、userdetailsservice。另外还有各类注解如@enableglobalmethodsecurity等。(以下代码含有一点jwt逻辑)

websecurityconfigureradapter:

 1 @configuration
 2 @enablewebsecurity
 3 @enableglobalmethodsecurity(prepostenabled = true)
 4 public class websecurityconfig extends websecurityconfigureradapter {
 5     @autowired
 6     private jwtauthenticationentrypoint unauthorizedhandler;
 7 
 8     @autowired
 9     private userdetailsservice userdetailsservice;
10 
11     @autowired
12     private custompostprocessor postprocessor;
13 
14     @autowired
15     public void configureauthentication(authenticationmanagerbuilder authenticationmanagerbuilder) throws exception {
16         authenticationmanagerbuilder
17                 .userdetailsservice(this.userdetailsservice)
18                 .passwordencoder(passwordencoder());
19     }
20 
21     @bean
22     public passwordencoder passwordencoder() {
23         return new bcryptpasswordencoder();
24     }
25 
26     @bean
27     public jwtauthenticationtokenfilter authenticationtokenfilterbean() throws exception {
28         return new jwtauthenticationtokenfilter();
29     }
30 
31     @override
32     protected void configure(httpsecurity httpsecurity) throws exception {
33         httpsecurity
34                 // we don't need csrf because our token is invulnerable
35                 .csrf().disable()
36                 .exceptionhandling().authenticationentrypoint(unauthorizedhandler).and()
37                 // don't create session
38                 .sessionmanagement().sessioncreationpolicy(sessioncreationpolicy.stateless).and()
39                 .authorizerequests()
40                 .antmatchers(httpmethod.options, "/**").permitall()
41                 .anyrequest().authenticated().withobjectpostprocessor(postprocessor);
42 
43         // custom jwt based security filter
44         httpsecurity
45                 .addfilterbefore(authenticationtokenfilterbean(), usernamepasswordauthenticationfilter.class);
46     }
47 }
view code

主要关注两个方法configureauthentication(authenticationmanagerbuilder authenticationmanagerbuilder)和configure(httpsecurity httpsecurity)。configureauthentication主要用于设置userdetailsservice,加载用户数据需要用到;configure用于设置资源的安全级别以及全局安全策略等。第41行withobjectpostprocessor,用于设置filterinvocationsecuritymetadatasource和accessdecisionmanager,它们两个用于鉴权,下面会讲到。

 1 @component
 2 public class custompostprocessor implements objectpostprocessor<filtersecurityinterceptor> {
 3     @autowired
 4     private customfiltersecuritymetadatasource customfiltersecuritymetadatasource;
 5 
 6     @autowired
 7     private customaccessdecisionmanager customaccessdecisionmanager;
 8 
 9     @override
10     public <t extends filtersecurityinterceptor> t postprocess(t fsi) {
11         fsi.setsecuritymetadatasource(customfiltersecuritymetadatasource); //1.路径(资源)拦截处理
12         fsi.setaccessdecisionmanager(customaccessdecisionmanager); //2.权限决策处理类
13         return fsi;
14     }
15 }
view code

userdetailservice(此处从数据库获取):

 1 @service
 2 public class jwtuserdetailsserviceimpl implements userdetailsservice {
 3 
 4     @autowired
 5     private userrepository userrepository;
 6 
 7     @override
 8     public userdetails loaduserbyusername(string username) throws usernamenotfoundexception {
 9         user user = userrepository.findbyusername(username);
10 
11         if (user == null) {
12             throw new usernamenotfoundexception(string.format("no user found with username '%s'.", username));
13         } else {
14             return jwtuserfactory.create(user);
15         }
16     }
17 }
view code

注意loaduserbyusername需要的参数名username是约定好的,在usernamepasswordauthenticationfilter中定义,value是从httpservletrequest中获取。

filterinvocationsecuritymetadatasource(用于获取当前请求资源所需的权限):

 1 /**
 2  * 路径拦截处理类
 3  * <p>
 4  * 如果路径属于允许访问列表,则不做拦截,放开访问;
 5  * <p>
 6  * 否则,获得路径访问所需角色,并返回;如果没有找到该路径所需角色,则拒绝访问。
 7  */
 8 @component
 9 public class customfiltersecuritymetadatasource implements filterinvocationsecuritymetadatasource {
10     @autowired
11     private apirepository apirepository;
12 
13     @override
14     public collection<configattribute> getattributes(object object) throws illegalargumentexception {
15         filterinvocation fi = (filterinvocation) object; //当前请求对象
16 
17         list<configattribute> configattributes = getmatcherconfigattribute(fi.getrequesturl(), fi.getrequest().getmethod()); // 获得访问当前路径所需要的角色
18 
19         return configattributes.size() > 0 ? configattributes : deniedrequest(); //返回当前路径所需角色,如果路径没有对应角色,则拒绝访问
20     }
21 
22     @override
23     public collection<configattribute> getallconfigattributes() {
24         return null;
25     }
26 
27     @override
28     public boolean supports(class<?> clazz) {
29         return filterinvocation.class.isassignablefrom(clazz);
30     }
31 
32     /**
33      * 获取当前路径以及请求方式获得所需要的角色
34      *
35      * @param url 当前路径
36      * @return 所需角色集合
37      */
38     private list<configattribute> getmatcherconfigattribute(string url, string method) {
39         set<authority> authorities = new hashset<>();
40         // 1.根据url的开头去数据库模糊查询相应的api
41 
42         string prefix = url.substring(0, url.lastindexof("/"));
43 
44         prefix = stringutil.isempty(prefix) ? url : prefix + "%";
45 
46         list<api> apis = apirepository.findbyurilikeandmethod(prefix, method);
47 
48         // 2.查找完全匹配的api,如果没有,比对pathmatcher是否有匹配的结果
49         apis.foreach(api -> {
50             string pattern = api.geturi();
51 
52             if (new antpathmatcher().match(pattern, url)) {
53                 list<resource> resources = api.getresources();
54 
55                 resources.foreach(resource -> {
56                     authorities.addall(resource.getauthorities());
57                 });
58             }
59         });
60 
61         return authorities.stream().map(authority -> new securityconfig(authority.getid().tostring())).collect(collectors.tolist());
62     }
63 
64     /**
65      * @return 默认拒绝访问配置
66      */
67     private list<configattribute> deniedrequest() {
68         return collections.singletonlist(new securityconfig("role_denied"));
69     }
70 }
view code

accessdecisionmanager:

 1 /**
 2  * 权限决策处理类
 3  *
 4  * 判断用户的角色,如果为空,则拒绝访问;
 5  *
 6  * 判断用户所有的角色中是否有一个包含在 访问路径允许的角色集合中;
 7  *
 8  * 如果有,则放开;否则拒绝访问;
 9  */
10 @component
11 public class customaccessdecisionmanager implements accessdecisionmanager {
12     @override
13     public void decide(authentication authentication, object object, collection<configattribute> configattributes) throws accessdeniedexception, insufficientauthenticationexception {
14         if (authentication == null) {
15             throw new accessdeniedexception("permission denied");
16         }
17 
18         //当前用户拥有的角色集合
19         list<string> rolecodes = authentication.getauthorities().stream().map(grantedauthority::getauthority).collect(collectors.tolist());
20 
21         //访问路径所需要的角色集合
22         list<string> configrolecodes = configattributes.stream().map(configattribute::getattribute).collect(collectors.tolist());
23         for (string rolecode : rolecodes) {
24             if (configrolecodes.contains(rolecode)) {
25                 return;
26             }
27         }
28 
29         throw new accessdeniedexception("permission denied");
30     }
31 
32     @override
33     public boolean supports(configattribute attribute) {
34         return true;
35     }
36 
37     @override
38     public boolean supports(class<?> clazz) {
39         return true;
40     }
41 }
view code

上述第19行和第22行分别为userdetailservice处取到的用户拥有的权限和filterinvocationsecuritymetadatasource取到的访问资源需要的权限,两者对比后即得出用户是否有访问该资源的权限。具体来说,鉴权的整个流程是:访问资源时,会通过abstractsecurityinterceptor拦截器拦截,其中会调用filterinvocationsecuritymetadatasource的方法来获取被拦截url所需的全部权限,再调用授权管理器accessdecisionmanager,这个授权管理器会通过spring的全局缓存securitycontextholder获取用户的权限信息,还会获取被拦截的url和被拦截url所需的全部权限,然后根据所配的策略(有:一票决定,一票否定,少数服从多数等),如果权限足够,则返回,权限不够则报错并调用权限不足页面。

题外话,登录认证可以认为并非认证授权的一部分,而是将身份令牌颁发给客户端的过程,之后客户端拿着身份令牌过来请求资源的时候才进入上面的认证授权环节。不过spring secuity中涉及到的认证方法可以简化登录认证的代码编写:

1 final authentication authentication = authenticationmanager.authenticate(
2         new usernamepasswordauthenticationtoken(username, password)
3 );
4 
5 securitycontextholder.getcontext().setauthentication(authentication);

其中authenticationmanager由框架提供,框架会根据上面说到的configureauthentication提供合适的authenticationmanager实例,认证失败时抛出异常,否则返回authenticatio令牌并为用户相关的securitycontext设置令牌。需要注意的是,securitycontext是存放在threadlocal中的,而且在每次权限鉴定的时候都是从threadlocal中获取securitycontext中对应的authentication所拥有的权限,并且不同的request是不同的线程,为什么每次都可以从threadlocal中获取到当前用户对应的securitycontext呢?在web应用中这是通过securitycontextpersistentfilter实现的,默认情况下其会在每次请求开始的时候从session中获取securitycontext,然后把它设置给securitycontextholder,在请求结束后又会将该securitycontext保存在session中,并且在securitycontextholder中清除。当用户第一次访问系统的时候,该用户没有securitycontext,待登录成功后,之后的每次请求就可以从session中获取到该securitycontext并把它赋予给securitycontextholder了,由于securitycontextholder已经持有认证过的authentication对象了,所以下次访问的时候也就不再需要进行登录认证了。

而上文说到的jwt,却是cookie/session一生黑。它的机制是http请求头部的令牌认证。我们可以借助它在session过期后也能正常的认证授权,而不需要用户重新登录。

 1 public class jwtauthenticationtokenfilter extends onceperrequestfilter {
 2 
 3     private final log logger = logfactory.getlog(this.getclass());
 4 
 5     @autowired
 6     private userdetailsservice userdetailsservice;
 7 
 8     @autowired
 9     private jwttokenutil jwttokenutil;
10 
11     @value("${jwt.header}")
12     private string tokenheader;
13 
14     @override
15     protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain chain) throws servletexception, ioexception {
16         final string requestheader = request.getheader(this.tokenheader);
17 
18         string username = null;
19         string authtoken = null;
20         if (requestheader != null && requestheader.startswith("bearer ")) {
21             authtoken = requestheader.substring(7);
22             try {
23                 username = jwttokenutil.getusernamefromtoken(authtoken);
24             } catch (illegalargumentexception e) {
25                 logger.error("an error occured during getting username from token", e);
26             } catch (exception e1) {
27                 logger.error(e1.getmessage());
28             }
29         }
30 
31         if (username != null && securitycontextholder.getcontext().getauthentication() == null) {
32 
33             // it is not compelling necessary to load the use details from the database. you could also store the information
34             // in the token and read it from it. it's up to you ;)
35             userdetails userdetails = this.userdetailsservice.loaduserbyusername(username);
36 
37             // for simple validation it is completely sufficient to just check the token integrity. you don't have to call
38             // the database compellingly. again it's up to you ;)
39             if (jwttokenutil.validatetoken(authtoken, userdetails)) {
40                 usernamepasswordauthenticationtoken authentication = new usernamepasswordauthenticationtoken(userdetails, null, userdetails.getauthorities());
41                 authentication.setdetails(new webauthenticationdetailssource().builddetails(request));
42                 logger.info("authenticated user " + username + ", setting security context");
43                 securitycontextholder.getcontext().setauthentication(authentication);
44             }
45         }
46 
47         chain.dofilter(request, response);
48     }
49 }
view code

当然也可以不借助spring security,单纯的实现jwt,那样就需要自己实现认证和授权过程了。

在spring boot 1.5中,我们可以依靠重写webmvcconfigureradapter的方法来添加自定义拦截器,消息转换器等;spring boot 2.0 后,该类被标记为@deprecated。方式改为实现webmvcconfigurer接口。在java中,拦截器(interceptor)和filter有所不同,前者更贴近aop概念,而后者只有前置执行。

对比:asp.net mvc相对清晰,可控性高;spring security隐藏了逻辑顺序,涉及类较多,关键步骤散落各处,层级不清,容易让新手困惑。还有其它的java认证框架如shiro,也很流行,此处按过不表。


非阻塞编程

在web开发领域,传统的实现异步的方式都比较复杂,比如 java 中的 nio,需要了解 channel,selector,buffer 这些概念,或者使用 netty 这样的网络框架。c/c++ 进行异步/非阻塞编程,则需要理解 select,poll,epoll 等概念,开发与维护门槛较高。而且这部分的开发与业务无关,那么封装底层机制,推出一套开发框架的必要性就显而易见了。概念上,.net习惯称为异步编程(asynchronous programming),java称之为响应式编程(reactive programming)。

.net/asynchronous programming

.net4.5(c#5.0,2012年)开始,引入async/await关键字,在语法层面上将异步编程变得如同同步处理般清晰流畅,并在短时内即推出了支持主流数据库的异步组件。从接收请求到数据操作,开发人员能很方便的将传统的同步代码迁移为异步模式。之后几年,如python(3.5)、nodejs(7.6)等纷纷效仿,成为事实上的语法标准。

java/reactive programming

我们得先从stream说起,stream本身和响应式编程没关系,但之后的reactive streams在某种程度上继承了它的某些概念。java 8 引入了stream,方便集合的聚合操作,它也支持lambda表达式作为操作参数,可以将其看做iterator。类似的语法在c#中也有,只是c#提供的是无侵入方式,集合本身就支持,更不用说stream这个概念多么让人混淆。相关资料:java 8 中的 streams api 详解

stream的映射操作有map和flatmap,类似c#中select和selectmany的区别。

reactive streams

历程

响应式流从2013年开始,作为提供非阻塞背压的异步流处理标准的倡议。

在2015年,出版了一个用于处理响应式流的规范和java api。 java api 中的响应式流由四个接口组成:publisher<t>,subscriber<t>,subscription和processor<t,r>。

jdk 9在java.util.concurrent包中提供了与响应式流兼容的api,它在java.base模块中。 api由两个类组成:flow和submissionpublisher<t>。flow类封装了响应式流java api。 由响应式流java api指定的四个接口作为嵌套静态接口包含在flow类中:flow.processor<t,r>,flow.publisher<t>,flow.subscriber<t>和flow.subscription。

是reactive streams的一个实现库。鄙人认为,reactive streams针对的场景是无边界数据的enumerate处理,无边界即数据/需求会被不停的生产出来,无法在事前确立循环规则(如循环次数);另一方面,它又提供了单次处理的处理规则(如每次处理多少条数据/需求)。相关资料:。

spring5.0开始提供响应式 web 编程支持,框架为spring webflux,区别于传统的spring mvc同步模式。spring webflux基于reactor,其语法类似js的promise,并有一些灵活有用的特性如延时处理返回。具体用法可参看:(5)spring webflux快速上手——响应式spring的道法术器 。就文中所说,目前(本文书写时间)spring data对mongodb、redis、apache cassandra和couchdb数据库提供了响应式数据访问支持,意即使用其它数据库的项目尚无法真正做到异步响应(最关键的io环节仍为线程同步)。

在java 7推出异步i/o库,以及servlet3.1增加了对异步i/o的支持之后,tomcat等servlet容器也随后开始支持异步i/o,然后spring webmvc也增加了对reactor库的支持,在spring mvc3.2版本已经支持异步模式。至于spring为何又推出一套webflux就不得而知了。

对比:非阻塞编程方面,java推进速度慢,目前的程度尚不能与几年前的.net相比,语法上,.net的async/await相比类promise语法更简洁,spring webflux在请求响应处理上有一些亮点。


其它

几个月前(美国当地时间9月25日),oracle官方宣布 java 11 (18.9 lts) 正式发布。java目前的版本发布策略是半年一版,每三年发布一个长期支持版本,java 11 是自 java 8 后的首个长期支持版本。目测java 8 开始的很多特性都参考了c#,比如异步编程、lambda、stream、var等等,这是一个好的现象,相互学习才能进步嘛。

.net的mvc模板引擎为默认为razor,它是专一且多情的,依赖于后端代码。而java平台常用的有很多,如freemarker,它独立于任何框架,可以将它看作复杂版的string.format,用在mvc中就是string.format(v,m),输出就是v模板绑定m数据后的html;还有spring boot自带的thymeleaf,它由于使用了标签属性做为语法,模版页面直接用浏览器渲染,使得前端和后端可以并行开发,窃以为这是兼顾便捷与运行效率的最佳前后端分离开发利器。

java8开始,可以在interface中定义静态方法和默认方法。在接口中,增加default方法, 是为了既有的成千上万的java类库的类增加新的功能, 且不必对这些类重新进行设计(类似于c#的扩展方法,但灵活度低,耦合度高)。

java8的optional有点类似于.net的xxxx?,都是简化是否为空判断。

java threadlocal类似于.net threadstaticattribute,都是提供线程内的局部变量[副本],这种变量在线程的生命周期内起作用。

java

fork/join:java 7 引入,方便我们将任务拆成子任务并行执行[并汇总结果后返回]。

静态引入:import static。导入静态方法。

使用匿名内部类方式初始化对象:

arraylist<student> stulist = new arraylist<student>() {
    {
        for (int i = 0; i < 100; i++) {
            add(new student("student" + i, random.nextint(50) + 50));
        }
    }
};

可参看java:双括号初始化 /匿名内部类初始化法

java 9 开始支持http/2,关于http/2的特点以及它相较于1.0、1.1版本的改进可自行百度,总之效率上提升很大。

spring3.0引入了@configuration。instead of using the xml files, we can use plain java classes to annotate the configurations by using the @configuration annotation. if you annotate a class with @configuration annotation, it indicates that the class is used for defining the beans using the @bean annotation. this is very much similar to the <bean/> element in the spring xml configurations.当然,xml配置和注解配置可以混用。我们若要复用它处定义的配置类,可使用@import注解,它的作用类似于将多个xml配置文件导入到单个文件。

spring中的后置处理器beanpostprocessor,用于在spring容器中完成bean实例化、配置以及其他初始化方法前后要添加一些自己逻辑处理。spring security中还有个objectpostprocessor,可以用来修改或者替代通过java方式配置创建的对象实例,可用在无法预先设置值如需要根据不同条件设置不同值的场景。

@value("#{}")与@value("${}"):前者用于赋予bean字段的值,后者用于赋予属性文件中定义的属性值。

servlet3.0开始,@webservlet, @webfilter, and @weblistener can be enabled by using @servletcomponentscan,不用在web.xml里面配置了。这无关spring,而是servlet容器特性。

@autowired是根据类型进行自动装配的。如果当spring上下文中存在不止一个userdao类型的bean时,就会抛出beancreationexception异常。我们可以使用@qualifier指明要装配的类型名称来解决这个问题。

 

其它参考资料:

基于注解的spring security原理解析

 

转载请注明本文出处:https://www.cnblogs.com/newton/p/9866506.html

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网