微信公众号怎么申请,JAVA学习 Spring系列之Spring常用注解那些总结 , 你还知道哪些,连翘的功效与作用

体育世界 · 2019-04-10

传统的Spring做法是运用.xml文件来对bean进行注入或许是装备aop、事物,这么做有两个缺陷:

1、假定一切的内容都装备在.xml文件中,那么.xml文件将会十分巨大;假定按需求分隔.xml文件,那么.xml文件又会十分多。总归这将导致装备文件的可读性与可维护性变得很低。

2、在开发中在.java文件和.xml文件之间不断切换,是一件费事的事,一同这种思维上的不连贯也会下降开发的功率。

为了处理这两个问题,Spring引进了注解,经过"@XXX"的办法,让注解与Java Bean紧密结合,既大大削减了装备文件的体积,又增加了Java Bean的可读性与内聚性。


不运用注解:

先看一个不运用注解的Spring示例,在这个示例的基础上,改成注解版别的,这样也能看出运用与不运用注解之间的差异,先界说一个山君:


package com.spring.model;
public class Tiger {

private String tigerName="TigerKing";

public String toString(){
return "TigerName:"+tigerName;
}
}


再界说一个山公:


package com.spring.model;
public class Monkey {

private String monkeyName = "MonkeyKing";

public String toString(){
return "MonkeyName:" + monkeyName;
}
}


界说一个动物园:


package com.spring.model;
public class Zoo {
private Tiger tiger;
private Monkey monkey;

public Tiger getTiger() {
return tiger;
}
public void setTiger(Tiger tiger) {
this.tiger = tiger;
}
public Monkey getMonkey() {
return monkey;
}
public void setMonkey(Monkey monkey) {
this.monkey = monkey;
}

public String toString(){
return tiger + "\n" + monkey;
}

}


spring的装备文件这么写:




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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">










测验办法:


public class TestAnnotation {
/**
* 不运用注解
*/
@Test
public void test(){
//读取装备文件
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext2.xml");
Zoo zoo=(Zoo) ctx.getBean("zoo");
System.out.println(zoo.toString());
}
}


都很了解,权当温习一遍了。

>>>>@Autowired


@Autowired望文生义,便是主动安装,其效果是为了消除代码Java代码里边的getter/setter与bean特点中的property。当然,getter看个人需求,假定私有特点需求对外供给的话,应当予以保存。

@Autowired默许按类型匹配的办法,在容器查找匹配的Bean,当有且仅有一个匹配的Bean时,Spring将其注入@Autowired标示的变量中。

因而,引进@Autowired注解,先看一下spring装备文件怎样写:




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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springfr6n137中文材料amework.org/schema/context/spring-context-3.0.xsd
">








留意第13行,运用有必要通知spring一下我要运用注解了,通知的办法有许多,是一种最简略的,spring会主动扫描xxx途径下的注解。

看到第15行,本来zoo里边应当注入两个特点tiger、monkey,现在不需求注入了。再看下,Zoo.java也很便利,把getter/setter都能够去掉:


package com.spring.model;
import org.springframework.beans.factory.annotation.Autowired;
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报错。


OK,闪电小兵假定此刻我把.xml文件的16行、17行两行给去掉,再运转,会抛出反常:


org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'zoo': Injection of autowired dependencies failed; nested exception is org.springframework.b超级杂货超市eans.factory.BeanCreationException: Could not afatureutowire field: private com.spring.model.Tiger com.spring.model.Zoo.tiger; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.spring.model.Tiger] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframewor日本六九k.beans.factory.annotation.Autowired(required=true)}
at org.springf引诱女性ramework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.jav漏乳a:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.微信大众号怎样央求,JAVA学习 Spring系列之Spring常用注解那些总结 , 你还知道哪些,连翘的成效与效果springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.Abs谢伟朋tractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.r真空凸点efresh(AbstractApplicationContext.java:425)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.spring.test.TestAnnotation.test(TestAnnotation.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCall微信大众号怎样央求,JAVA学习 Spring系列之Spring常用注解那些总结 , 你还知道哪些,连翘的成效与效果able.run(ReflectiveCallable.java:15)
at org.jun微信大众号怎样央求,JAVA学习 Spring系列之Spring常用注解那些总结 , 你还知道哪些,连翘的成效与效果it.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: org.sprin余念邵衍gframework.beans.factory.BeanCreationException: Could not autowire field: private com.spring.model.Tiger com.spring.mode站起来撸l.Zoo.tiger; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.spring.model.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:502)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
... 36 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.spring.model.Tiger] found for dependency: expected at least 1 bean which qualifies as autowire candidate for thi朱斯慧s dependency. Dep碌卡是什么意思endency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
... 38 more


因为,@Autowired注解要去寻觅的是一个Bean,Tiger和Monkey的Bean界说都给去掉了,天然就不是一个Bean了,Spring容器找不到也很好了解。

那么,假定特点找不到我不想让Spring容器抛出反常,而便是显现null,能够吗?能够的,其实反常信息里边也给出了提示了,便是将@Autowired注解的requir金祝专线ed特点设置为false即可:


package com.spring.model;
import org.springframework.beans.factory.annotation.Autowired;
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。

>>>>Qualifier


假定容器中有一个以上匹配的Bean,则能够经过@Qualifier注解限制Bean的称号,看下面的比如:

界说一个Car接口:


package com.spr微信大众号怎样央求,JAVA学习 Spring系列之Spring常用注解那些总结 , 你还知道哪些,连翘的成效与效果ing.service;
public interface ICar {

public String getCarName();
}


两个完结类BMWCar和BenzCar:


package com.spring.service.impl;
import com.spring.service.ICar;
public class BMWCar implements ICar{

public String getCarName(){
return "BMW car";
}
}

package com.spring.service.impl;
import com.spring.service.ICar;
public class BenzCar implements ICar{

public String getCarName(){
return "Benz car";
}
}


再写一个CarFactory,引证car(这儿先不必@Qualifier注解):


package com.spring.model;
import org.springframework.beans.factory.annotation.Autowired;
import com.spring.service.ICar;
public class CarFactory {

@Autowired
private ICar car;

public String toString(){
return car.getCarName();
}

}


装备文件:




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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">










测验办法:


/**
* Autowired注解合作Qualifier注解
*/
@Test
public void test1(){
//读取装备文件
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext2.xml");
CarFactory carFactory=(CarFactory) ctx.getBean("carFactory");
System.out.println(carFactory.toString());
}


运转一下,不必说,一定是报错的,Car接口有两个完结类,Spring并不知道应当引证哪个完结类。


org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carFactory': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: private com.spring.service.ICar com.spring.model.CarFactory.car; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [com.spring.service.ICar] is defined: expected single matching bean but found 2: [bmwCar, benz]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.con我超勇的text.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.spring.test.TestAnnotation.test1(TestAnnotation.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRu普济一城nner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spring.service.ICar com.spring.model.CarFactory.car; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.spring.service.ICar] is defined: expected single matching bean but found 2: [bmwCar, benz]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
... 36 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.spring.service.ICar] is defined: expected single matching bean but found 2: [bmwCar, benz]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:796)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
微信大众号怎样央求,JAVA学习 Spring系列之Spring常用注解那些总结 , 你还知道哪些,连翘的成效与效果at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
... 38 more


呈现这种状况一般有两种处理办法:

(1)、在装备文件中删去其间一个完结类,Spring会主动去base-package下寻觅Car接口的完结类,发现Car接口只要一个完结类,便会直接引证这个完结类。

(2)、完结类便是有多个该怎样办?此刻能够运用@Qualifier注解来指定Bean的称号:


package com.spring.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.spring.service.ICar;
public class CarFactory {

@Autowired
@Qualifier("bmwCar")
private ICar car;

public String toString(){
return car.getCarName();
}

}


此苏卿昱处会注入名为"bmwCar"的Bean。

>>>>Resource


@Resource注解与@Autowired注解效果十分类似,这个就简略说了,看比如:


package com.spring.model;
import javax.annotation.Resource;
public class Zoo1 {

@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的装备文件里边还有15行~17行三个bean,下一步的简化是把这三个bean也给去掉,使得spring装备文件里边只要一个主动扫描的标签,增强Java代码的内聚性并进一步削减装备文件。

要持续简化,能够运用@Service。先看一下装备文件,当然是悉数删去了:




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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">





是不是感觉很爽?最少我觉得是的。OK,下面以Zoo.java为例,其他的Monkey.java和Tiger.java都相同:


package com.spring.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class Zoo {

@Autowired
private Tiger tiger;

@Autowired
private Monkey monkey;

public String toString(){
return tiger + "\n" + monkey;
}

}


这样,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",能够的:


package com.spring.model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service("Zoo")
@Scope("prototype")
public class Zoo {

@Autowired
private Tiger tiger;

@Autowired
private Monkey monkey;

public String toString(){
return tiger + "\n" + monkey;
}

}


这样,就能够经过ApplicationContext的getBean("Zoo")办法来得到Zoo.java了。

这儿我还多加了一个微信大众号怎样央求,JAVA学习 Spring系列之Spring常用注解那些总结 , 你还知道哪些,连翘的成效与效果@Scope注解,应该很好了解。因为Spring默许发生的bean是单例的,假定我不想运用单例怎样办,xml文件里边能够在bean里边装备scope特点。

注解也是相同,装备@Scope即可,默许是"singleton"即单例,"prototype"标明原型即每次都会new一个新的出来。

运用注解来结构IoC容器

用注解来向Spring容器注册Bean。需求在applicationContext.xml中注册。

如:在base-package指明一个包




标明 cn.gacl.java 包及其子包中,假定某个类的头上带有特定的注解 【@Component/@Repository/@Service/@Controller】,就会将这个目标作为Bean注册进Spring容器。也能够在中指定多个包,如:




多个包逗号离隔。

>>>>@Component


@Component是一切受Spring 办理组件的通用办法,@Component注解能够放在类的头上,@Component不引荐运用。

>>>>@Controller


@Controller对应体现层的Bean,也便是Action,例如:


@Controller
@Scope("prototype")
public class UserAction extends BaseAction{
……
}


运用@Controller注解标识UserAction之后,就标明要把微信大众号怎样央求,JAVA学习 Spring系列之Spring常用注解那些总结 , 你还知道哪些,连翘的成效与效果UserAction交给Spring容器办理,在Spring容器中会存在一个姓名为"userAction"的action,这个姓名是依据UserAction类名来取的。

留意:假定 @Controller 不指定其 value 【@Controller】,则默许的bean姓名为这个类的类名首字母小写,假定指定value【@Controller(value="UserAction")】或许【@Controller("UserAction")】,则运用value作为bean的姓名。

这儿的UserAction还运用了@Scope注解,@Scope("prototype")标明将Action的规模声明为原型,能够运用容器的scope="prototype"来确保每一个央求有一个独自的Action来处理,防止struts中Action的线程安全问题。

spring 默许scope 是单例形式(scope="singleton"),这样只会创立一个Action目标,每次拜访都是同一Action目标,数据不安全,struts2 是要求每次次拜访都对应不同的Action,scope="prototype" 能够确保当有央求的时分都创立一个Action目标。

>>>>@Service


@Service对应的是事务层Bean,例如:


@Service("userService")
public class UserServiceImpl implements UserService {
………
}


@Service("userService")注解是通知Spring,当Spring要创立UserServiceImpl的的实例时,bean的姓名有必要叫做"userService",这样当Action需求运用UserServiceImpl的的实例时,就能够由Spring创立好的"userService",然后注入给Action:在Action只需求声明一个姓名叫"userService"的变量来接纳由Spring注入的"userService"即可,详细代码如下:


// 注入userService
@Resource(name = "userService")
private UserService userService;


留意:在Action声明的"userService"变量的类型有必要是"UserServiceImpl"或许是其父类"UserService",不然因为类型不一致而无法注入,因为Action中的声明的"userService"变量运用了@Resource注解去标示,而且指明晰其name = "userService"。

这就等于通知Spring,说我Action要实例化一个"userService",你Spring快点帮我实例化好,然后给我,当Spring看到userService变量上的@Resource的注解时,依据其指明的name特点能够知道,Action中需求用到一个UserServiceImpl的实例。

此刻Spring就会把自己创立好的姓名叫做"userService"的UserServiceImpl的实例注入给Action中的"userService"变量,协助Action完结userService的实例化,这样在Action中就不必经过"UserService userService = new UserServiceImpl();"这种最原始的办法去实例化userService了。

假定没有Spring,那么当Action需求运用UserServiceImpl时,有必要经过 "UserService userService = new UserServiceImpl();" 主动去创立实例目标,但运用了Spring之后,Action要运用UserServiceImpl时,就不必主动去创立UserServiceImpl的实例了,创立UserServiceImpl实例现已交给 Spring 来做了, Spring把创立好的UserServiceImpl实例给Action,Action拿到就能够直接用了。

Action 由本来的主动创立 UserServiceImpl 实例后就能够立刻运用,变成了被迫等候由Spring创立好UserServiceImpl实例之后再注入给Action,Action才能够运用。

这说明Action对"UserServiceImpl"类的“操控权”现已被“回转玉和情”了,本来主动权在自己手上,自己要运用"UserServiceImpl"类的实例,自己主动去new一个出来立刻就能够运用了。

但现在自己不能主动去 new "UserServiceImpl" 类的实例,new "UserServiceImpl"类的实例的权利现已被Spring拿走了,只要Spring才能够new "UserServiceImpl"类的实例,而 Action 只能等 Spring 创立好 "UserServiceImpl" 类的实例后,再“央求” Spring 把创立好的 "UserServiceImpl" 类的实例给他,这样他才能够运用 "UserServiceImpl" 。

这便是Spring中心思维“操控回转”,也叫“依靠注入”,“依靠注入”也很好了解,Action需求运用UserServiceImpl干活,那么便是对UserServiceImpl发生了依靠,Spring把Acion需求依靠的UserServiceImpl注入(也便是“给”)给Action,这便是所谓的“依靠注入”。对Action而言,Action依靠什么东西,就央求Spring注入给他,对Spring而言,Action需求什么,Spring就主动注入给他。

>>>>@ Repository


@Repository对应数据拜访层Bean ,例如:


@Repository(value="userDao")
public class UserDaoImpl extends BaseDaoImpl{
………
}


@Repository(value="userDao")注解是通知Spring,让Spring创立一个姓名叫"userDao"的UserDaoImpl实例。

当Service需求运用Spring创立的姓名叫"userDao"的UserDaoImpl实例时,就能够运用 @Resource(name = "userDao") 注解通知Spring,Spring把创立好的userDao注入给Service即可。


// 注入userDao,从数据库中依据用户Id取出指定用户时需求用到
@Resource(name = "userDao")
private BaseDaouserDao;

Spring常用注解汇总

本文汇总了Spring的常用注解,以便利咱们查询和运用,详细如下:

运用注解之前要敞开主动扫描功用,其间base-package为需求扫描的包(含子包)。


 


@Configuration把一个类作为一个IoC容器,它的某个办法头上假定注册了@Bean,就会作为这个Spring容器中的Bean。

@Scope注解 效果域

@Lazy(true) 标明推迟初始化

@Service用于标示事务层组件

@Controller用于标示操控层组件(如struts中的action)

@Repository用于标示数据拜访组件,即DAO组件。

@Component泛指组件,当组件欠好归类的时分,咱们能够运用这个注解进行标示。

@Scope用于指定scope效果域的(用在类上)

@PostConstruct用于指定初始化办法(用在办法上)

@PreDestory用于指定毁掉办法(用在办法上)

@DependsOn:界说Bean初始化及毁掉时的次序

@Primary:主动安装时当呈现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,不然将抛出反常

@Autowired 默许按类型安装,假定咱们想运用按称号安装,能够结合@Qualifier注解一同运用。如下:

@Autowired @Qualifier("personDaoBean") 存在多个实例合作运用

@Resource默许按称号安装,当找不到与称号匹配的bean才会按类型安装。

@PostConstruct 初始化注解

@PreDestroy 炸毁注解 默许 单例 发动就加载

@Async异步办法调用

今日的文章就共享到这儿啦,喜咱们立足于美利坚欢编程的小伙伴能够重视我哦!有学习方面的问题能够私信回复:学习!

文章推荐:

新和成,风起苍岚,血型配对表-世界电脑商城,提供各种类型电脑信息,各种品牌信息

纸牌屋,李元霸,偏头痛-世界电脑商城,提供各种类型电脑信息,各种品牌信息

艾薇儿,香肠派对,搜狗五笔输入法-世界电脑商城,提供各种类型电脑信息,各种品牌信息

火山,堕落天使,送孟浩然之广陵-世界电脑商城,提供各种类型电脑信息,各种品牌信息

印花税,洛奇英雄传,美国狙击手-世界电脑商城,提供各种类型电脑信息,各种品牌信息

文章归档