spring4注解
- 格式:pdf
- 大小:885.11 KB
- 文档页数:11
spring注解@Component、@Service等⾃动⽣成bean的命名规则参考链接:信息来源今天碰到⼀个问题,写了⼀个@Service的bean,类名⼤致为:CUserxml配置:<context:component-scan base-package="com.xxx.xx.x"/>结果启动报错:No bean named 'cUser' is defined,即找不到名为cUser的beanbean的名字不是我预期的"cUser",临时将bean的名字硬性指定成了cUser来解决的,即:@Service("cUser")在⽹上找了半天,看到有位兄弟说得很有道理,引⽤⼀下(以下内容引⽤⾃篇⾸链接):但还是觉得⽐较奇怪,之前⼀直以为Spring对注解形式的bean的名字的默认处理就是将⾸字母⼩写,再拼接后⾯的字符,但今天看来不是这样的。
回来翻了⼀下原码,原来还有另外的⼀个特殊处理:当类的名字是以两个或以上的⼤写字母开头的话,bean的名字会与类名保持⼀致/** * Derive a default bean name from the given bean definition.* <p>The default implementation simply builds a decapitalized version* of the short class name: e.g. "mypackage.MyJdbcDao" -> "myJdbcDao".* <p>Note that inner classes will thus have names of the form* "outerClassName.InnerClassName", which because of the period in the* name may be an issue if you are autowiring by name.* @param definition the bean definition to build a bean name for* @return the default bean name (never {@code null})*/protected String buildDefaultBeanName(BeanDefinition definition) {String shortClassName = ClassUtils.getShortName(definition.getBeanClassName());return Introspector.decapitalize(shortClassName);}/** * Utility method to take a string and convert it to normal Java variable* name capitalization. This normally means converting the first* character from upper case to lower case, but in the (unusual) special* case when there is more than one character and both the first and* second characters are upper case, we leave it alone.* <p>* Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays* as "URL".** @param name The string to be decapitalized.* @return The decapitalized version of the string.*/public static String decapitalize(String name) {if (name == null || name.length() == 0) {return name;} // 如果发现类的前两个字符都是⼤写,则直接返回类名if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&Character.isUpperCase(name.charAt(0))){return name;} // 将类名的第⼀个字母转成⼩写,然后返回 char chars[] = name.toCharArray();chars[0] = Character.toLowerCase(chars[0]); return new String(chars);}。
【SpringFramework】Spring⼊门教程(三)使⽤注解配置本⽂主要介绍四个⽅⾯:(1) 注解版本IOC和DI(2) Spring纯注解(3) Spring测试(4) SpringJDBC - Spring对数据库的操作使⽤注解配置Spring⼊门说在前⾯学习基于注解的IoC配置,⼤家脑海⾥⾸先得有⼀个认知,即注解配置和xml配置要实现的功能都是⼀样的,都是要降低模块间的耦合度。
仅仅只是配置的形式不⼀样。
关于实际的开发中到底使⽤xml还是注解,每家公司有着不同的使⽤习惯。
所以这两种配置⽅式我们都需要掌握。
基于注解配置的⽅式也已经逐渐代替xml配置。
所以我们必须要掌握使⽤注解的⽅式配置Spring。
配置步骤注意:如果使⽤Eclipse需要先安装了STS插件,或者使⽤STS开发⼯具创建项⽬。
本⽂使⽤IDEA进⾏演⽰。
1.2.1. 第⼀步:拷贝必备jar包到⼯程的lib⽬录。
注意:在基于注解的配置中,我们还要多拷贝⼀个aop的jar包。
如下图:1.2.2. 第⼆步:在类的根路径下创建⼀个任意名称的xml⽂件(不能是中⽂)注意:基于注解整合时,Spring配置⽂件导⼊约束时需要多导⼊⼀个context命名空间下的约束。
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:context="/schema/context"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsd/schema/context/schema/context/spring-context.xsd"></beans>1.2.3. 第⼆步:创建⼀个服务类创建⼀个测试的服务类,并且加⼊使⽤@Component注解,声明该类允许注⼊到Spring容器package org.cjw.service;import ponent;/*使⽤注解配置时,需要将Spring框架启动就创建对象的类表⽰为组件类表⽰组件类使⽤@Component注解*/@Componentpublic class CustomerService {public void save() {System.out.println("-保存数据-");}}1.2.4. 第四步在spring的配置⽂件加⼊扫描注解<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:context="/schema/context"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsd/schema/context/schema/context/spring-context.xsd"><!-- 声明扫描包及其⼦包的类,如果发现有组件注解的类,就创建对象并加⼊到容器中去 --><context:component-scan base-package="org.cjw" /></beans>1.2.5. 第五步:测试调⽤代码package org.cjw.test;import org.cjw.service.CustomerService;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class CustomerServiceTest {@Testpublic void testSave() {ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");CustomerService customerService = context.getBean(CustomerService.class);customerService.save();}}--测试结果,如果可以调⽤服务⽅法,测试成功。
Spring注解@component、@service、@Autowired等作⽤与区别1、@Service⽤于标注业务层组件2、@Controller⽤于标注控制层组件(如struts中的action)3、@Repository⽤于标注数据访问组件,即DAO组件.4、@Component泛指组件,当组件不好归类的时候,我们可以使⽤这个注解进⾏标注。
5、@Autowired与@Resource的区别: @Autowired由Spring提供,只按照byType注⼊,默认情况下必须要求依赖对象存在,如果要允许null值,可以设置它的required属性为false。
如果想使⽤名称装配可以结合@Qualifier注解进⾏使⽤。
public class UserService {@Autowired@Qualifier(name="userDao1")private UserDao userDao;} @Resource由J2EE提供,默认按照byName⾃动注⼊,Spring将@Resource注解的name属性解析为bean的名字,type属性则解析为bean的类型。
所以如果使⽤name属性,则使⽤byName的⾃动注⼊策略,⽽使⽤type属性则使⽤byType⾃动注⼊策略。
①如果同时指定了name和type,则从Spring上下⽂中找到唯⼀匹配的bean进⾏装配,找不到则抛出异常。
②如果指定了name,则从上下⽂中查找名称(id)匹配的bean进⾏装配,找不到则抛出异常。
③如果指定了type,则从上下⽂中找到类似匹配的唯⼀bean进⾏装配,找不到或是找到多个,都会抛出异常。
④如果既没有指定name,⼜没有指定type,则⾃动按照byName⽅式进⾏装配;如果没有匹配,则回退为⼀个原始类型进⾏匹配,如果匹配则⾃动装配。
总结:@Resource的作⽤相当于@Autowired,只不过@Autowired按byType⾃动注⼊。
1.1SpringBoot环境配置和常⽤注解Spring Boot常⽤注解:@Service: 注解在类上,表⽰这是⼀个业务层bean@Controller:注解在类上,表⽰这是⼀个控制层bean@Repository: 注解在类上,表⽰这是⼀个数据访问层bean@Component:注解在类上,表⽰通⽤bean ,value不写默认就是类名⾸字母⼩写@Autowired:按类型注⼊.默认属性required= true;当不能确定Spring 容器中⼀定拥有某个类的Bean 时,可以在需要⾃动注⼊该类Bean 的地⽅可以使⽤@Autowired(required = false),这等于告诉Spring:在找不到匹配Bean时也不抛出BeanCreationException 异常。
@Autowired 和 @Qualifier 结合使⽤时,⾃动注⼊的策略就从byType 转变byName 了。
@Autowired可以对成员变量、⽅法以及构造函数进⾏注释,⽽@Qualifier 的标注对象是成员变量、⽅法⼊参、构造函数⼊参。
正是由于注释对象的不同,所以 Spring 不将 @Autowired 和 @Qualifier 统⼀成⼀个注释类。
@Resource:按名称装配区别:@Resource默认按照名称⽅式进⾏bean匹配,@Autowired默认按照类型⽅式进⾏bean匹配@Resource(importjavax.annotation.Resource;)是J2EE的注解,@Autowired(importorg.springframework.beans.factory.annotation.Autowired;)是Spring的注解@Configuration:注解在类上,表⽰这是⼀个IOC容器,相当于spring的配置⽂件,java配置的⽅式。
IOC容器的配置类⼀般与@Bean 注解配合使⽤,⽤@Configuration 注解类等价与 XML 中配置 beans,⽤@Bean 注解⽅法等价于 XML 中配置 bean。
Spring常⽤的⼀些注解说明@Configuration从Spring3.0,@Configuration⽤于定义配置类,可替换xml配置⽂件,被注解的类内部包含有⼀个或多个被@Bean注解的⽅法。
这些⽅法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进⾏扫描,并⽤于构建bean定义。
@Bean@Bean注解⽤于告诉⽅法,产⽣⼀个Bean对象,然后这个Bean对象交给Spring管理。
产⽣这个Bean对象的⽅法Spring只会调⽤⼀次,随后这个Spring将会将这个Bean对象放在⾃⼰的IOC容器中。
SpringIOC 容器管理⼀个或者多个bean,这些bean都需要在@Configuration注解下进⾏创建,在⼀个⽅法上使⽤@Bean注解就表明这个⽅法需要交给Spring进⾏管理。
@Autowired、@Resource@Resource和@Autowired注解都是⽤来实现依赖注⼊的。
只是@AutoWried按by type⾃动注⼊,⽽@Resource默认按byName⾃动注⼊。
♣ @Autowired@Autowired具有强契约特征,其所标注的属性或参数必须是可装配的。
如果没有Bean可以装配到@Autowired所标注的属性或参数中,⾃动装配就会失败,抛出NoSuchBeanDefinitionException.@Autowired可以对类成员变量、⽅法及构造函数进⾏标注,让 spring 完成 bean ⾃动装配的⼯作。
@Autowired 默认是按照类去匹配,配合 @Qualifier 指定按照名称去装配 bean。
♣ @Resource@Resource是JDK提供的注解,有两个重要属性,分别是name和type。
@Resource依赖注⼊时查找bean的规则既不指定name属性,也不指定type属性,则⾃动按byName⽅式进⾏查找。
Spring注解执⾏的默认顺序对于同⼀个⽅法,上⾯加了n个注解,如下所⽰。
@AnnotationOne @AnnotationTwo public void test() { ……………………………… } 如果,不加order来强制表⽰顺序的话,这2个注解执⾏的默认顺序是什么样⼦的呢?经查阅Spring官⽅⽂档,可知:What happens when multiple pieces of advice all want to run at the same join point? Spring AOP follows the same precedence rules as AspectJ to determine the order of advice execution. The highest precedence advice runs first “on the way in” (so, given two pieces of before advice, the one with highest precedence runs first). “On the way out” from a join point, the highest precedence advice runs last (so, given two pieces of after advice, the one with the highest precedence will run second).When two pieces of advice defined in different aspects both need to run at the same join point, unless you specify otherwise, the order of execution is undefined. You can control the order of execution by specifying precedence. This is done in the normal Spring way by either implementing the org.springframework.core.Ordered interface in the aspect class or annotating it with the Order annotation. Given two aspects, the aspect returning the lower value from Ordered.getValue() (or the annotation value) has the higher precedence.When two pieces of advice defined in the same aspect both need to run at the same join point, the ordering is undefined (since there is no way to retrieve the declaration order through reflection for javac-compiled classes). Consider collapsing such advice methods into one advice method per join point in each aspect class or refactor the pieces of advice into separate aspect classes that you can order at the aspect level.中⽂翻译如下:当在同⼀Join Point上出现多个Advice时怎么办呢? Spring AOP遵循与AspectJ相同的优先级规则来确定建议执⾏的顺序。
Spring注解使⽤场景启始版本模式注解@Repository数据仓储模式注解Spring Framework 2.0 @Component通⽤组件模式注解Spring Framework 2.5 @Service服务模式注解Spring Framework 2.5 @Controller Web控制器模式注解Spring Framework 2.5 @Configuration配置类模式注解Spring Framework 3.0装配注解@ImportResource替换XML元素<import>Spring Framework 2.5 @Import限定@Autowired依赖注⼊范围(导⼊对应的 @Configuration 标识类)Spring Framework 3.0 @ComponentScan扫描制定package下标注Spring模式注解的类Spring Framework 3.1依赖注⼊注解@Autowired Bean依赖注⼊,⽀持多种依赖查找⽅式Spring Framework 2.5 @Qualifier细粒度的@Autowired依赖查找⽅式Spring Framework 2.5 @Resource [JAVA注解]Bean依赖注⼊,仅⽀持名称依赖查找⽅式Spring Framework 2.5 Bean定义注解@Bean替换XML元素<bean/>Spring Framework 3.0 @DependsOn替换XML属性<bean depends-on="..."/>Spring Framework 3.0 @Lazy替代XML属性<bean lazy-init="true|false"/>Spring Framework 3.0 @Primary替换XML属性<bean primary="true|false"/>Spring Framework 3.0 @Role替换XML属性<bean role="..."/>Spring Framework 3.1 @Lookup替代XML属性<bean lookup-method="..."/>Spring Framework 4.1条件装配注解@Profile配置化条件装配Spring Framework 3.1 @Conditional编程条件装配Spring Framework 4.0配置属性注解@PropertySource配置属性抽象PropertySource注解Spring Framework 3.1 @PropertySources@PropertySource集合注解(实现 JAVA 8 @Repeatable相似的功能)Spring Framework 4.0⽣命周期回调注解@PostConstruct替换XML元素<bean init-method="..."/>或InitializingBean Spring Framework 2.5 @PreDestory替换XML元素<bean destory-method="..."/>或 DisposableBean Spring Framework 2.5注解属性注解@AliasFor别名注解属性,实现复⽤的⽬的Spring Framework 4.2性能注解@Indexed提升Spring模式注解的扫描效率(编译时会在classPath下⽣成 META-INF/ponents⽂件)Spring Framework 5.0Spring核⼼注解Spring核⼼注解归类如下:。
Spring中Bean管理的常⽤注解在Spring中,主要⽤于管理bean的注解分为四⼤类:1.⽤于创建对象。
2.⽤于给对象的属性注⼊值。
3.⽤于改变作⽤的范围。
4.⽤于定义⽣命周期。
这⼏个在开发中经常接触到,也可以说每天都会遇见。
其中创建对象是重点,Spring中创建对象的有四个:分别是@Component,@Controller,@Service,@Repository。
对于@Component注解:把资源让Spring来管理,相当于xml中的配置的Bean。
属性:value:指定Bean中的id。
如果不指定value属性,默认Bean的id是当前类的类名,⾸字母⼩写。
在开发中的场景是这样的,其实是在实现类中加⼊即可:@Component("customerService")public class CustomerServiceImpl implements CustomerService{public void save() {System.out.println("顾客保存⽅法");}}⽽其它的三个注解都是针对⼀个衍⽣注解,它们的作⽤及属性都是⼀模⼀样的。
只不过提供了更加明确的语义化。
@Controller:⼀般⽤于表现层的注解。
@Service:⼀般⽤于业务层的注解。
@responsitory:⼀般⽤于持久层的注解。
⽤法与以上相同,这⾥不做过多的解释。
要理解这个三个注解就是让标注类本⾝的⽤途清晰⽽已。
接下来,聊聊⽤于给对象的属性注⼊值得问题。
Spring给我们提出了注⼊数据的注解有:@Value,@Autowired,@Qualifier,@Resource。
其中@Value:注⼊基本数据类型和String类型数据,它的属性value⽤于指定值。
@Autowired这个⽤法是⽐较重要的,它能够⾃动按照类型注⼊。
当使⽤注解注⼊属性时,set⽅法可以省略。
SpringBoot注解解析⼤全(⾮常全哦!)使⽤注解的优势:1.采⽤纯java代码,不在需要配置繁杂的xml⽂件2.在配置中也可享受⾯向对象带来的好处3.类型安全对重构可以提供良好的⽀持4.减少复杂配置⽂件的同时亦能享受到springIoC容器提供的功能⼀、注解详解(配备了完善的释义)------(可采⽤ctrl+F 来进⾏搜索哦~~~~也可以收藏⽹页这样以后就不⽤往复查询了哦)@SpringBootApplication:申明让spring boot⾃动给程序进⾏必要的配置,这个配置等同于:@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三个配置。
@ResponseBody:表⽰该⽅法的返回结果直接写⼊HTTP response body中,⼀般在异步获取数据时使⽤,⽤于构建RESTful的api。
在使⽤@RequestMapping后,返回值通常解析为跳转路径,加上@esponsebody后返回结果不会被解析为跳转路径,⽽是直接写⼊HTTP response body中。
⽐如异步获取json数据,加上@Responsebody后,会直接返回json数据。
该注解⼀般会配合@RequestMapping⼀起使⽤。
@Controller:⽤于定义控制器类,在spring项⽬中由控制器负责将⽤户发来的URL请求转发到对应的服务接⼝(service层),⼀般这个注解在类中,通常⽅法需要配合注解@RequestMapping。
@RestController:⽤于标注控制层组件(如struts中的action),@ResponseBody和@Controller的合集。
@RequestMapping:提供路由信息,负责URL到Controller中的具体函数的映射。
@EnableAutoConfiguration:SpringBoot⾃动配置(auto-configuration):尝试根据你添加的jar依赖⾃动配置你的Spring应⽤。
SpringBoot中常⽤注解及各种注解作⽤本篇⽂章将介绍⼏种SpringBoot 中常⽤注解其中,各注解的作⽤为:@PathVaribale 获取url中的数据@RequestParam 获取请求参数的值@GetMapping 组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写@RestController是@ResponseBody和@Controller的组合注解。
@PathVaribale 获取url中的数据看⼀个例⼦,如果我们需要获取Url=localhost:8080/hello/id中的id值,实现代码如下:@RestControllerpublic class HelloController {@RequestMapping(value="/hello/{id}",method= RequestMethod.GET)public String sayHello(@PathVariable("id") Integer id){return "id:"+id;}}@RequestParam 获取请求参数的值直接看⼀个例⼦,如下@RestControllerpublic class HelloController {@RequestMapping(value="/hello",method= RequestMethod.GET)public String sayHello(@RequestParam("id") Integer id){return "id:"+id;}}在浏览器中输⼊地址:localhost:8080/hello?id=1000,可以看到如下的结果:当我们在浏览器中输⼊地址:localhost:8080/hello?id ,即不输⼊id的具体值,此时返回的结果为null。