原文出处: locality

1.@Component是Spring定义的一个通用注解,可以注解任何bean。

2.@Scope定义bean的作用域,其默认作用域是”singleton”,除此之外还有prototype,request,session和global session。


案例:@Component和@Scope用法分析:

BeanAnnotation类:

 @Scope
@Component
public class BeanAnnotation { public void say(String arg) {
System.out.println("BeanAnnotation : " + arg);
} public void myHashCode() {
System.out.println("BeanAnnotation : " + this.hashCode());
} }

junit4测试类→TestBeanAnnotation类:

 @RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanAnnotation extends UnitTestBase { public TestBeanAnnotation() {
super("classpath*:spring-beanannotation.xml");
} @Test
public void testSay() {
BeanAnnotation bean = super.getBean("beanAnnotation");
bean.say("This is test.");
} @Test
public void testScpoe() {
BeanAnnotation bean = super.getBean("beanAnnotation");
bean.myHashCode();
bean = super.getBean("beanAnnotation");
bean.myHashCode();
} }

Spring配置文件→spring-beanannotation.xml:

 <context:component-scan base-package="com.beanannotation"></context:component-scan>

我们先从Spring配置文件分析,base-package="com.beanannotation"说明我们只处理这个包名下面的注解。

然后分析BeanAnnotation类,有一个say的方法。假设我们不清楚这是一个什么类型(注:Service或者DAO)的类,我们可以用一个通用的注解@Component。

最后分析TestBeanAnnotation类,testSay方法里super.getBean("beanAnnotation")是从IOC的容器中取到这个bean,并调用bean的say方法。

提出问题的时间到了,当我们super.getBean的时候是通过bean的id从IOC容器中获取的,那么这个id是什么呢?因为在我们添加@Component到BeanAnnotation类上的时候,默认的id为beanAnnotation。如果指定了@Component的名称,譬如指定为@Component(”bean”)的时候,在单元测试的时候就必须把super.getBean得到的id与之相对应才能测试成功。

在这里我把@Scope注解单独分离出来分析,在TestBeanAnnotation类里面有一个testScpoe方法。在BeanAnnotation类里面有一个myHashCode方法,可能大家有些疑惑,为什么要用this.hashCode()?因为@Scope指定的是bean的作用域,为了保证测试类的结果准确明了,所以采用哈希码值来判断是否为同一个对象。


3.@Repository、@Service、@Controller是更具有针对性的注解。
PS:这里我们需要明白这三个注解是基于@Component定义的注解哦:
①、@Repository通常用于注解DAO类,也就是我们常说的持久层。
②、@Service通常用于注解Service类,也就是服务层。
③、@Controller通常用于Controller类,也就是控制层(MVC)。

4.@Autowired理解为“传统”的setter方法,可以用在setter方法上,也可以用在构造器或者成员变量,能够进行Spring Bean的自动装配。


案例:@Autowired用法分析一:

Spring配置文件→spring-beanannotation.xml:

 <context:component-scan base-package="com.beanannotation"></context:component-scan>

SimpleMovieLister类:

 public class SimpleMovieLister {

     private MovieFinder movieFinder;

     @Autowired(required=false)
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
} }

在默认的情况下,如果找不到合适的bean将会导致autowiring失败抛出异常,我们可以将@Autowired注解在这个set方法上,标记required=false来避免。但是,这不是一个必须的,如果找不到movieFinder的实例,是不会抛出异常的,只有在使用的时候发现movieFinder为null,在这种情况下,就要求我们在使用的时候,首先判断movieFinder是不是为null,如果是就会报空指针异常 。

值得注意的是,我们知道每个类可以有很多个构造器,但是在使用@Autowired的时候,有且只能有一个构造器能够被标记为required=true(注:required的默认值为false)。


案例:@Autowired用法分析二:

BeanImplOne类:

 @Order
@Component
public class BeanImplOne implements BeanInterface { }

BeanImplTwo类:

 @Order
@Component
public class BeanImplTwo implements BeanInterface { }

BeanInterface类:

 public interface BeanInterface {

 }

BeanInvoker类:

 @Component
public class BeanInvoker { @Autowired
private List<BeanInterface> list; @Autowired
private Map<String, BeanInterface> map; public void say() {
if (null != list && 0 != list.size()) {
for (BeanInterface bean : list) {
System.out.println(bean.getClass().getName());
}
} else {
System.out.println(" list is null !");
} if (null != map && 0 != map.size()) {
for (Map.Entry<String, BeanInterface> entry : map.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue().getClass().getName());
}
} else {
System.out.println("map is null !");
}
}
}

测试类TestInjection:

 @RunWith(BlockJUnit4ClassRunner.class)
public class TestInjection extends UnitTestBase { public TestInjection() {
super("classpath:spring-beanannotation.xml");
} @Test
public void testMultiBean() {
BeanInvoker invoker = super.getBean("beanInvoker");
invoker.say();
} }

首先,我们清楚BeanImplOne类和BeanImplTwo类是实现了BeanInterface接口的,在BeanInvoker类里面我们定义了list和map,我们通过@Autowired注解把BeanImplOne类和BeanImplTwo类注解进入其中。那么怎么证实是@Autowired注解把这两个类注入到list或者map中的呢?那么请看if循环语句和foreach循环打印,通过这个逻辑判断,如果能够打印出BeanImplOne类和BeanImplTwo类的路径名,就说明这样是可以的。如果有些小伙伴可能不信,那么可以试着不使用@Autowired注解,看结果怎么样。

测试类没有什么好说的,各位小伙伴有没有注意到@Order注解呢?这里需要解释的就是,如果在@Order注解里面输入执行的数字,比如1或者2,那么打印出来的路径名就会按顺序,也就是说通过指定@Order注解的内容可以实现优先级的功能。


5.@ImportResource注解引入一个资源,对应一个xml文件
6.@Value注解从资源文件中,取出它的key并赋值给当前类的成员变量


案例:@ImportResource和@Value用法分析:

MyDriverManager类:

 public class MyDriverManager {

     public MyDriverManager(String url, String userName, String password) {
System.out.println("url : " + url);
System.out.println("userName: " + userName);
System.out.println("password: " + password);
} }

config.xml:

 <context:property-placeholder location="classpath:/config.properties"/>

StoreConfig类:

 @Configuration
@ImportResource("classpath:config.xml")
public class StoreConfig { @Value("${jdbc.url}")
private String url; @Value("${jdbc.username}")
private String username; @Value("${jdbc.password}")
private String password; @Bean
public MyDriverManager myDriverManager() {
return new MyDriverManager(url, username, password);
}

这个案例我们使用注解配置jdbc数据库的连接,首先创建一个内含构造器的MyDriverManager类,然后配置config.xml里面的资源文件路径,以便@ImportResource注解获取,最后配置StoreConfig类。(注意url、username、password也必须要和数据库的保持一致哦)

详解StoreConfig类:首先我们定义三个成员变量,然后给每一个成员变量打上一个@value注解,注意@value里面的内容一定是资源文件里面的key值。这里的@ImportResource注解就是指明一个资源文件,在这个资源文件里面获取到对应的数据。那么@Configuration注解是用来干嘛的呢?为什么不用@Component注解呢?其实是这样的,@Component注解用于将所标注的类加载到 Spring 环境中,这时候是需要配置component-scan才能使用的,而@Configuration注解是Spring 3.X后提供的注解,它用于取代XML来配置 Spring。


7.@Bean注解用来标识配置和初始化一个由SpringIOC容器管理的新对象的方法,类似XML中配置文件的<bean/>

ps:默认的@Bean注解是单例的,那么有什么方式可以指定它的范围呢?所以这里才出现了@Scope注解

8.@Scope注解,在@Scope注解里面value的范围和Bean的作用域是通用的,proxyMode的属性是采用哪一种的单例方式(一种是基于接口的注解,一种是基于类的代理)


案例:@Bean和@Scope用法分析:

 @Bean
@Scope(value ="session",proxyMode = "scopedProxyMode.TARGET_CLASS")
public UserPreferences userPreferences(){
return new userPreferences();
} @Bean
public service userService(){
UserService service =new SimpleUserService();
service.setUserPreferences(userPreferences);
return service;
}

浅谈Spring框架注解的用法分析的更多相关文章

  1. 浅谈Spring框架

    一.Spring简介 Spring 是一个开源框架,是为了解决企业应用程序开发复杂性而创建的.框架的主要优势之一就是其分层架构, 分层架构允许您选择使用哪一个组件,同时为 J2EE 应用程序开发提供集 ...

  2. 浅谈Spring @Order注解的使用(转)

    注解@Order或者接口Ordered的作用是定义Spring IOC容器中Bean的执行顺序的优先级,而不是定义Bean的加载顺序,Bean的加载顺序不受@Order或Ordered接口的影响: 1 ...

  3. 浅谈Spring中的Quartz配置

    浅谈Spring中的Quartz配置 2009-06-26 14:04 樊凯 博客园 字号:T | T Quartz是一个强大的企业级任务调度框架,Spring中继承并简化了Quartz,下面就看看在 ...

  4. 【SSH学习笔记】浅谈SSH框架

    说在前面 本学期我们有一门课叫做Java EE,由陈老师所授,主要讲的就是Java EE 中的SSH框架. 由于陈老师授课风格以及自己的原因导致学了整整一学期不知道在讲什么,所以才有了自己重新学习总结 ...

  5. 浅谈Spring的两种配置容器

    浅谈Spring的两种配置容器 原文:https://www.jb51.net/article/126295.htm 更新时间:2017年10月20日 08:44:41   作者:黄小鱼ZZZ     ...

  6. Spring的注解@Qualifier用法

    Spring的注解@Qualifier用法在Controller中需要注入service那么我的这个server有两个实现类如何区分开这两个impl呢?根据注入资源的注解不同实现的方式有一点小小的区别 ...

  7. JavaWeb_(Spring框架)注解配置

    系列博文 JavaWeb_(Spring框架)xml配置文件  传送门 JavaWeb_(Spring框架)注解配置 传送门 Spring注解配置 a)导包和约束:基本包.aop包+context约束 ...

  8. 手撸ORM浅谈ORM框架之基础篇

    好奇害死猫 一直觉得ORM框架好用.功能强大集众多优点于一身,当然ORM并非完美无缺,任何事物优缺点并存!我曾一度认为以为使用了ORM框架根本不需要关注Sql语句如何执行的,更不用关心优化的问题!!! ...

  9. 手撸ORM浅谈ORM框架之Add篇

    快速传送 手撸ORM浅谈ORM框架之基础篇 手撸ORM浅谈ORM框架之Add篇 手撸ORM浅谈ORM框架之Update篇 手撸ORM浅谈ORM框架之Delete篇 手撸ORM浅谈ORM框架之Query ...

随机推荐

  1. Android之——ContentResolver查询的三种方式

    转载请注明出处:http://blog.csdn.net/l1028386804/article/details/47785491 今天做到一个小项目.查询手机中短信的信息,当然得去系统暴露出来的数据 ...

  2. Problem-1000:A + B Problem

    Problem-1000:A + B Problem Sample Code: C 代码: [code] #include int main() { int a,b; while(~scanf(&qu ...

  3. spring学习笔记(五)

    1.后置通知 需求:调用相应业务方法后,完成资源的关闭. a. 在beans.xml中配置 .... <beans> <!--配置被代理对象--> <bean id=&q ...

  4. nginx location 或操作

    location ~* (\.(7z|bat|bak|ini|log|rar|sql|swp|tar|zip|gz|git|asp|svn)|/phpmyadmin) { deny all; }

  5. 转 spring官方文档中文版

    转 http://blog.csdn.net/tangtong1/article/details/51326887另附码云地址 https://gitee.com/free/spring-framew ...

  6. Atitit. camel分词器 分词引擎 camel拆分 的实现设计

    Atitit. camel分词器 分词引擎 camel拆分 的实现设计 1. camel分词器1 1.1. 实现的界定符号大写字母小写字母数字1 1.2. 特殊处理 对于JSONObject 多个大写 ...

  7. 在modelsim中加入quartus仿真库

    找到modelsim安装目录下的modelsim.ini文件. 将modelsim.ini的只读属性去掉. 打开quartus软件.选择Launch Simulation Library Compil ...

  8. 一起talk C栗子吧(第八十七回:C语言实例--使用管道进行进程间通信概述)

    各位看官们,大家好.上一回中咱们说的是进程间通信的样例.这一回咱们说的样例是:使用管道进行进程间通信. 闲话休提,言归正转. 让我们一起talk C栗子吧! 我们在前面的的章回中介绍了使用管道进行进程 ...

  9. 循环杀死Mysql sleep进程脚本

    #!/bin/sh while : do n=`mysqladmin processlist -uadmin -p***|grep -i sleep |wc -l` date=`date +%Y%m% ...

  10. Linux 开机自动挂载分区

    参考:http://linuxso.com/linuxrumen/3658.html 参考:http://www.jb51.net/os/RedHat/213998.html 查看磁盘UUID信息 [ ...