SSM框架中出现的几种注解的理解
转自IT·达人原文 Spring5:@Autowired注解、@Resource注解和@Service注解,有删改。
传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop、事物,这么做有两个缺点:
1、如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大;如果按需求分开.xml文件,那么.xml文件又会非常多。总之这将导致配置文件的可读性与可维护性变得很低
2、在开发中在.java文件和.xml文件之间不断切换,是一件麻烦的事,同时这种思维上的不连贯也会降低开发的效率
为了解决这两个问题,Spring引入了注解,通过"@XXX"的方式,让注解与Java Bean紧密结合,既大大减少了配置文件的体积,又增加了Java Bean的可读性与内聚性。
不适用注解,及使用@Autowired、@Resource和 @Service注解含义将在本文中进行阐述。
一、不使用注解
先看一个不使用注解的Spring示例,在这个示例的基础上,改成注解版本的,这样也能看出使用与不使用注解之间的区别。
定义类老虎、猴子、动物园
public class Tiger
{
private String tigerName = "TigerKing"; public String toString()
{
return "TigerName:" + tigerName;
}
} public class Monkey
{
private String monkeyName = "MonkeyKing"; public String toString()
{
return "MonkeyName:" + monkeyName;
}
}
public class Zoo
{
private Tiger tiger;
private Monkey monkey; public void setTiger(Tiger tiger)
{
this.tiger = tiger;
} public void setMonkey(Monkey monkey)
{
this.monkey = monkey;
} public Tiger getTiger()
{
return tiger;
} public Monkey getMonkey()
{
return monkey;
} public String toString()
{
return tiger + "\n" + monkey;
}
}
不适用注解,直接使用IOC时,spring的配置文件这么写:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd"
default-autowire="byType"> <bean id="zoo" class="com.xrq.bean.Zoo" >
<property name="tiger" ref="tiger" />
<property name="monkey" ref="monkey" />
</bean> <bean id="tiger" class="com.xrq.domain.Tiger" />
<bean id="monkey" class="com.xrq.domain.Monkey" /> </beans>
二、@Autowired Beans注入(常用方法)
顾名思义,@Autowired就是自动装配,其作用是为了消除代码Java代码里面的getter/setter与bean属性中的property。
当然,getter看个人需求,如果私有属性需要对外提供的话,应当予以保留。因此,引入@Autowired注解。
spring配置文件的写法:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <context:component-scan base-package="com.xrq" /> <bean id="zoo" class="com.xrq.bean.Zoo" />
<bean id="tiger" class="com.xrq.domain.Tiger" />
<bean id="monkey" class="com.xrq.domain.Monkey" /> </beans>
注意第10行,使用必须告诉spring一下我要使用注解了,告诉的方式有很多,<context:component-scan base-package="xxx" />是一种最简单的,spring会自动扫描xxx路径下的注解。
看到第12行,原来zoo里面应当注入两个属性tiger、monkey,现在不需要注入了。
再看下,Zoo.java也很方便,把getter/setter都可以去掉。
public class Zoo
{
@Autowired
private Tiger tiger; @Autowired
private Monkey monkey; public String toString()
{
return tiger + "\n" + monkey;
}
}
这里@Autowired注解的意思就是,当Spring发现@Autowired注解时,将自动在代码上下文中找到和其匹配(默认是类型匹配)的Bean,并自动注入到相应的地方去。
有一个细节性的问题是,假如bean里面有两个property,Zoo.java里面又去掉了属性的getter/setter并使用@Autowired注解标注这两个属性那会怎么样?
答案是 Spring会按照xml优先的原则去Zoo.java中寻找这两个属性的getter/setter,导致的结果就是初始化bean报错。
假设此时我把.xml文件的13行、14行两行给去掉,再运行,会抛出异常。
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Zoo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xrq.domain.Tiger com.xrq.bean.Zoo.ttiger; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xrq.domain.Tiger] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:835)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.xrq.test.MyTest.main(MyTest.java:13)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xrq.domain.Tiger com.xrq.bean.Zoo.ttiger; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xrq.domain.Tiger] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:571)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 13 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xrq.domain.Tiger] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:543)
... 15 more
因为,@Autowired注解要去寻找的是一个Bean,Tiger和 Monkey的Bean定义都给去掉了,自然就不是一个Bean了,Spring容器找不到也很好理解。
那么,如果属性找不到我不想让Spring容器抛 出异常,而就是显示null,可以吗?
可以的,其实异常信息里面也给出了提示了,就是将@Autowired注解的required属性设置为false 即可。
public class Zoo
{
@Autowired(required = false)
private Tiger tiger; @Autowired(required = false)
private Monkey monkey; public String toString()
{
return tiger + "\n" + monkey;
}
}
此时,找不到tiger、monkey两个属性,Spring容器不再抛出异而是认为这两个属性为null。
三、@Autowired 接口注入
上面的比较简单,我们只是简单注入一个Java类,那么如果有一个接口,有多个实现,Bean里引用的是接口名,又该怎么做呢?
比如有一个Car接口、两个实现类BMW和Benz:
@Service
public interface Car
{
public String carName();
} @Service
public class BMW implements Car
{
public String carName()
{
return "BMW car";
}
} @Service
public class Benz implements Car
{
public String carName()
{
return "Benz car";
}
}
写一个CarFactory,引用Car
@Service
public class CarFactory
{
@Autowired
private Car car; public String toString()
{
return car.carName();
}
}
不用说,一定是报错的,Car接口有两个实现类,Spring并不知道应当引用哪个实现类。这种情况通常有两个解决办法:
1、删除其中一个实现类,Spring会自动去base-package下寻找Car接口的实现类,发现Car接口只有一个实现类,便会直接引用这个实现类。
2、实现类就是有多个该怎么办?此时可以使用@Qualifier注解。
@Service
public class CarFactory
{
@Autowired
@Qualifier("BMW")
private Car car; public String toString()
{
return car.carName();
}
}
注意@Qualifier注解括号里面的应当是Car接口实现类的类名,我之前试的时候一直以为是bean的名字,所以写了"bMW",结果一直报错。
四、@Resource
把@Resource注解放在@Autowired下面说,是因为它们作用非常相似,这个就简单说了,例子过后点明一下@Resource和@Autowired的区别。先看一下@Resource,直接写Zoo.java了:
@Service
public class Zoo
{
@Resource(name = "tiger")
private Tiger tiger; @Resource(type = Monkey.class)
private Monkey monkey; public String toString()
{
return tiger + "\n" + monkey;
}
}
这是详细一些的用法,说一下@Resource的装配顺序:
1、@Resource后面没有任何内容,默认通过name属性去匹配bean,找不到再按type去匹配
2、指定了name或者type则根据指定的类型去匹配bean
3、指定了name和type则根据指定的name和type去匹配bean,任何一个不匹配都将报错
然后,区分一下@Autowired和@Resource两个注解的区别:
1、@Autowired默认按照byType方式进行bean匹配,@Resource默认按照byName方式进行bean匹配
2、@Autowired是Spring的注解,@Resource是J2EE的注解,这个看一下导入注解的时候这两个注解的包名就一清二楚了
Spring属于第三方的,J2EE是Java自己的东西,因此,建议使用@Resource注解,以减少代码和Spring之间的耦合。
五、@Service
上面这个例子,还可以继续简化,因为spring的配置文件里面还有12行~14行三个bean,下一步的简化是把这三个bean也给去掉,使得spring配置文件里面只有一个自动扫描的标签,增强Java代码的内聚性并进一步减少配置文件。
要继续简化,可以使用@Service。先看一下配置文件,当然是全部删除了:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <context:component-scan base-package="com.xrq" /> </beans>
是不是感觉很爽?起码我觉得是的。OK,下面以Zoo.java为例,其余的Monkey.java和Tiger.java都一样:
@Service
public class Zoo
{
@Autowired
private Tiger ttiger; @Autowired
private Monkey mmonkey; public String toString()
{
return ttiger + "\n" + mmonkey;
}
}
这样,Zoo.java在Spring容器中存在的形式就是"zoo",即可以通过ApplicationContext的getBean("zoo")方法来得到Zoo.java。
@Service注解,其实做了两件事情:
1、声明Zoo.java是一个bean,这点很重要,因为Zoo.java是一个bean,其他的类才可以使用@Autowired将Zoo作为一个成员变量自动注入
2、Zoo.java在bean中的id是"zoo",即类名且首字母小写。
如果,我不想用这种形式怎么办,就想让Zoo.java在Spring容器中的名字叫做"Zoo",可以的:
@Service
@Scope("prototype")
public class Zoo
{
@Autowired
private Monkey monkey;
@Autowired
private Tiger tiger; public String toString()
{
return "MonkeyName:" + monkey + "\nTigerName:" + tiger;
}
}
这样,就可以通过ApplicationContext的getBean("zoo")方法来得到Zoo.java了。
这里我还多加了一个@Scope注解,应该 很好理解。因为Spring默认产生的bean是单例的,假如我不想使用单例怎么办,xml文件里面可以在bean里面配置scope属性。
注解也是一 样,配置@Scope即可,默认是"singleton"即单例,"prototype"表示原型即每次都会new一个新的出来。
六、补充
最后再补充一个我发现的细节。假如animal包下有Tiger、domain包下也有Tiger,它们二者都加了@Service注解,那么在Zoo.java中即使明确表示我要引用的是domain包下的Tiger,程序运行的时候依然会报错。
细想,其实这很好理解,两个Tiger都使 用@Service注解标注,意味着两个Bean的名字都是"tiger",那么我在Zoo.java中自动装配的是哪个Tiger呢?不明确,因 此,Spring容器会抛出BeanDefinitionStoreException异常,Caused by:
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'monkey' for bean class [com.xrq.domain.Monkey] conflicts with existing,
non-compatible bean definition of same name and class [com.xrq.animal.Monkey]
SSM框架中出现的几种注解的理解的更多相关文章
- SSM框架中IoC、DI与AOP的理解
框架封装了普通项目中程序员需要重复书写的代码和调用过程,就比如说在传统的jsp项目中,我们的controller接收到前端的请求然后程序员就需要去开发Dao层,里面还涉及数据库的连接和存储过程的代码, ...
- 在SSM框架中我设置拦截器filter不能通过注解获取到实现类
我在用注解注入实现类的时候,出现了这样的错误:如以下截图: 这个地方报出的错误是说明我的一个接口类型的类没有获取到,后来我就想要是我的实现类没有获取到那么我就直接new一个实现类然后再进行调用就会出现 ...
- maven springMVC SSM框架中 出现的406 (Not Acceptable)
首先,需要清楚,http state 406代表什么意思: 406是HTTP协议状态码的一种,表示无法使用请求的特性来响应请求的网页.一般指客户端浏览器不接受所请求页面的MIME类型. 出现这样的错误 ...
- JAVA使用log4j(另SSM框架中使用log4j)
1.引入jar包 log4j-1.2.13.jar 2.src下建立配置文件:log4j.properties #不+All,只写后一种LOG log4j.rootLogger =ALL,system ...
- SSM框架中的前后端分离
认识前后端分离 在传统的web应用开发中,大多数的程序员会将浏览器作为前后端的分界线.将浏览器中为用户进行页面展示的部分称之为前端,而将运行在服务器,为前端提供业务逻辑和数据准备的所有代码统称为后端. ...
- SSM整合中遇到的不能扫描注解的bug
我的开发环境为: ubuntu14.04LTS 64bit; Spring Tool Suite 3.5.0.RELEASE Maven 3.2.3 SSM整合中遇到的不能扫描注解的bug 最终解决 ...
- SSM框架中,controller的action返回参数给vue.js
在SSM框架中,controller的action中,返回的是视图,即jsp页面或是ModelAndView,若是通过axios给vue传值的话,需要转换为字符串或是user实体类对象. 使用@Res ...
- SSM框架中数据库无法连接的问题
首先是SSM框架中所有的配置都是没有问题的,而且项目在其他人的环境上也能正常访问数据库:那么最有可能的就是数据库版本的问题导致数据库连接不上,服务器给我的报错是: 15:37:25.902 [C3P0 ...
- SSM框架中的注解,配置和控制器相关笔记
常规SSM实例 探索SSM理论的前提,应该是在对框架基础的运作方式有一定了解,以下是个人Android后台项目,用SSM框架快速搭建,以下是代码,主要 观察结构. 代码结构: model实体类 Ida ...
随机推荐
- ECharts图表tooltip显示时超出canvas图层解决方法
我们在做ECharts图表的时候可能会遇到tooltip显示时超出了canvas图层范围,并且被其它z-index较高的div容器遮盖,这是悬浮展示信息就看不全,我们根据官网文档的配置项查询发现con ...
- systemd服务内容详解
systemd是Linux下的一种init软件,由Lennart Poettering带头开发,并在LGPL 2.1及其后续版本许可证下开源发布.其开发目标是提供更优秀的框架以表示系统服务间的依赖关系 ...
- HDU 2181 哈密顿绕行世界问题 (DFS)
题目链接:https://vjudge.net/contest/185350#problem/C 题目大意:一个规则的实心十二面体,它的 20个顶点标出世界著名的20个城市,你从一个城市出发经过每个城 ...
- 学习Leader选举算法
读书笔记:<从Paxos到Zookeeper 分布式一致性原理与实践> 选举的前提约定 观察者不参与选举,只有跟随者才参与选举. 优先选事务ID(ZXID)大的,事务Id相同再优先选服务器 ...
- Merge k Sorted Lists——分治与堆排序(需要好好看)
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 1 ...
- react + redux 实现幻灯片
写在前面: 这一篇是我 使用scss + react + webpack + es6实现幻灯片 的进阶篇,效果请点我,将会使用上redux的基础用法,因为一开始没有理解好redux的用法,单纯看文档, ...
- Windows下配置Apache服务器
第一步:下载最新Apache. 下载网址:http://www.apachehaus.com/cgi-bin/download.plx 第二步:把下载文件解压缩到一个工作目录.D:\Apache 第三 ...
- AciveX接口事件的手动实现
为了理解ActiveX事件的运作原理,特意做了如下实验 初试化过程: try { CLSID clsid; HRESULT hr=::CLSIDFromProgID(L"MSWinsock. ...
- Django+Nginx+uwsgi搭建自己的博客(四)
由于在上篇博文中仍然介绍了相当多的后端部分,导致原定于上篇介绍的前端部分“跳票”到了这篇.在此篇博文中,我将会介绍Users App和主页的前端部分,从而形成我们博客的一个雏形. 在前端部分,我们主要 ...
- springMVC+freemarker实现自定义标签
在开发过程中,有些需要引用到重复的页面,或者动态的数据 修改数据库是可以实现,但是太麻烦了. freemarker自定义标签在开发中用途很广,就说个入门实例吧 基于springmvc. 首先需要导入对 ...