基于注解的方式配置bean(基于注解配置Bean,基于注解来装配Bean的属性)

在classpath中扫描组件

组件扫描(component scanning):Spring能够从classpath下自动扫描,侦测和实例化具有特定注解的组件。

特定组件包括:

-@Component:基本注解,表示了一个受Spring管理的组件

-@Respository:标识持久层组件

-@Service:标识服务层组(业务层)件

-@Controller:标识表现层组件

对于扫描到的组件,Spring有默认的命名策略:使用非限定类名,第一个字母小写,也可以在注解中通过value属性值标识组件的名称。

当在组件类上使用了特定的注解之后,还需要在Spring的配置文件中声明<context:component-scan>:

-base-package属性指定一个需要扫描的基类包,Spring容器将会扫描这个基类包里面及其子包中的所有类。

-当需要扫描多个包时,可以使用逗号分隔。

-如果仅希望扫描特定的类而不非基包下的所有类,可以使用resource-pattern属性过滤特定的类,示例:

<context:component-scan
base-package="com.logan.spring.beans"
resource-pattern="autowire/*.class"/>

-<context:include-filter>子节点表示要包含的目标类

-<context:exclude-filter>子节点表示要排除在外的目标

-<context:component-scan>下可以拥有若干个<context:include-filter>和<context:exclude-filter>子节点。

看代码

package logan.spring.study.annotation;

import org.springframework.stereotype.Component;

@Component
public class TestObject { }
package logan.spring.study.annotation.repository;

import org.springframework.stereotype.Repository;

@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository { @Override
public void save() {
// TODO Auto-generated method stub
System.out.println("UserRepository Save..."); } }
package logan.spring.study.annotation.service;

import org.springframework.stereotype.Service;

@Service
public class UserService { public void add(){
System.out.println("UserService add...");
}
}
package logan.spring.study.annotation.controller;

import org.springframework.stereotype.Controller;

@Controller
public class UserController { public void execute(){
System.out.println("UserController execute...");
} }

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package="logan.spring.study.annotation"></context:component-scan> </beans>
package logan.spring.study.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import logan.spring.study.annotation.controller.UserController;
import logan.spring.study.annotation.repository.UserRepository;
import logan.spring.study.annotation.service.UserService; public class Main {
public static void main(String[] args) {
System.out.println(1);
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml");
System.out.println(2);
TestObject to = (TestObject) ctx.getBean("testObject");
System.out.println(to); UserController userController = (UserController) ctx.getBean("userController");
System.out.println(userController); UserService userService = (UserService) ctx.getBean("userService");
System.out.println(userService); UserRepository userRepository = (UserRepository) ctx.getBean("userRepository");
System.out.println(userRepository);
} }
package logan.spring.study.annotation.repository;

public interface UserRepository {

    void save();

}

返回的结果为

五月 24, 2017 10:25:12 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@42110406: startup date [Wed May 24 22:25:11 CST 2017]; root of context hierarchy
五月 24, 2017 10:25:12 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-annotation.xml]
logan.spring.study.annotation.TestObject@78ac1102
logan.spring.study.annotation.controller.UserController@2de8284b
logan.spring.study.annotation.service.UserService@396e2f39
logan.spring.study.annotation.repository.UserRepositoryImpl@a74868d

这里使用的jar包有:

可以如下改规则:(通过resource-pattern指定扫描资源)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan
base-package="logan.spring.study.annotation"
resource-pattern="repository/*.class" ></context:component-scan> </beans>
package logan.spring.study.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import logan.spring.study.annotation.controller.UserController;
import logan.spring.study.annotation.repository.UserRepository;
import logan.spring.study.annotation.service.UserService; public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml");
// TestObject to = (TestObject) ctx.getBean("testObject");
// System.out.println(to); // UserController userController = (UserController) ctx.getBean("userController");
// System.out.println(userController); // UserService userService = (UserService) ctx.getBean("userService");
// System.out.println(userService); UserRepository userRepository = (UserRepository) ctx.getBean("userRepository");
System.out.println(userRepository);
} }

输出的结果为:

五月 24, 2017 10:30:25 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@42110406: startup date [Wed May 24 22:30:25 CST 2017]; root of context hierarchy
五月 24, 2017 10:30:25 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-annotation.xml]
logan.spring.study.annotation.repository.UserRepositoryImpl@32eebfca

<context:include-filter>和<context:exclude-filter>子节点支持多种类型的过滤表达式:

类别 示例 说明
annotation  com.logan.XxxAnnotation 所有标注了XxxAnnotation的类,该类型采用目标类是否标注了某个注解进行过滤 
assinable  com.logan.XxxService 所有继承或扩展XxxService的类,该类型采用目标类是否基层或扩展某个特定类型进行过滤 
aspecct com.logan.*Service+ 所有类名以Service结束的类以及继承或者扩展它们的类,该类型采用AspectJ表达式进行过滤。 
regex  com.logan.\anno\.* 所有com.logan.anno包下的类,该类型采用正则表达式根据类的类名进行过滤 
custom   采用XxxTypeFilter,通过代码的方式定义过滤规则,该类必须实现org.springframework.core.type.TypeFilter接口。 

看如下配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan
base-package="logan.spring.study.annotation">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"></context:exclude-filter></context:component-scan> </beans>
package logan.spring.study.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import logan.spring.study.annotation.controller.UserController;
import logan.spring.study.annotation.repository.UserRepository;
import logan.spring.study.annotation.service.UserService; public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml");
TestObject to = (TestObject) ctx.getBean("testObject");
System.out.println(to); UserController userController = (UserController) ctx.getBean("userController");
System.out.println(userController); UserService userService = (UserService) ctx.getBean("userService");
System.out.println(userService); // UserRepository userRepository = (UserRepository) ctx.getBean("userRepository");
// System.out.println(userRepository);
} }

下面是输出结果

五月 25, 2017 10:21:53 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@42110406: startup date [Thu May 25 22:21:53 CST 2017]; root of context hierarchy
五月 25, 2017 10:21:53 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-annotation.xml]
logan.spring.study.annotation.TestObject@75881071
logan.spring.study.annotation.controller.UserController@2a70a3d8
logan.spring.study.annotation.service.UserService@289d1c02

看如下代码:

package logan.spring.study.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import logan.spring.study.annotation.controller.UserController;
import logan.spring.study.annotation.repository.UserRepository;
import logan.spring.study.annotation.service.UserService; public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml");
// TestObject to = (TestObject) ctx.getBean("testObject");
// System.out.println(to);
//
// UserController userController = (UserController) ctx.getBean("userController");
// System.out.println(userController);
//
// UserService userService = (UserService) ctx.getBean("userService");
// System.out.println(userService); UserRepository userRepository = (UserRepository) ctx.getBean("userRepository");
System.out.println(userRepository);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan
base-package="logan.spring.study.annotation" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"></context:include-filter></context:component-scan> </beans>

输出结果

五月 26, 2017 9:37:08 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@42110406: startup date [Fri May 26 21:37:08 CST 2017]; root of context hierarchy
五月 26, 2017 9:37:08 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-annotation.xml]
logan.spring.study.annotation.repository.UserRepositoryImpl@78ac1102

<context:include-filter>子节点包含哪些表达式的组件,该子节点需要use-default-filter配合使用。

看如下配置:(指定不包括谁)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan
base-package="logan.spring.study.annotation">
<context:exclude-filter type="assignable" expression="logan.spring.study.annotation.repository.UserRepository"></context:exclude-filter>
</context:component-scan> </beans>
package logan.spring.study.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import logan.spring.study.annotation.controller.UserController;
import logan.spring.study.annotation.repository.UserRepository;
import logan.spring.study.annotation.service.UserService; public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml");
TestObject to = (TestObject) ctx.getBean("testObject");
System.out.println(to); UserController userController = (UserController) ctx.getBean("userController");
System.out.println(userController); UserService userService = (UserService) ctx.getBean("userService");
System.out.println(userService); UserRepository userRepository = (UserRepository) ctx.getBean("userRepository");
System.out.println(userRepository);
}
}

输出结果:

五月 27, 2017 11:04:35 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@42110406: startup date [Sat May 27 11:04:35 CST 2017]; root of context hierarchy
五月 27, 2017 11:04:36 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-annotation.xml]
logan.spring.study.annotation.TestObject@289d1c02
logan.spring.study.annotation.controller.UserController@22eeefeb
logan.spring.study.annotation.service.UserService@17d0685f
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userRepository' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
at logan.spring.study.annotation.Main.main(Main.java:22)

看下面配置:(指定包含谁)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan
base-package="logan.spring.study.annotation" use-default-filters="false">
<context:include-filter type="assignable" expression="logan.spring.study.annotation.repository.UserRepository"></context:include-filter>
</context:component-scan> </beans>
package logan.spring.study.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import logan.spring.study.annotation.controller.UserController;
import logan.spring.study.annotation.repository.UserRepository;
import logan.spring.study.annotation.service.UserService; public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-annotation.xml");
// TestObject to = (TestObject) ctx.getBean("testObject");
// System.out.println(to);
//
// UserController userController = (UserController) ctx.getBean("userController");
// System.out.println(userController);
//
// UserService userService = (UserService) ctx.getBean("userService");
// System.out.println(userService); UserRepository userRepository = (UserRepository) ctx.getBean("userRepository");
System.out.println(userRepository);
}
}

输出结果:

五月 27, 2017 11:07:17 上午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@42110406: startup date [Sat May 27 11:07:17 CST 2017]; root of context hierarchy
五月 27, 2017 11:07:17 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-annotation.xml]
logan.spring.study.annotation.repository.UserRepositoryImpl@13eb8acf

Spring入门第十四课的更多相关文章

  1. Spring入门第十九课

    后置通知 看代码: package logan.study.aop.impl; public interface ArithmeticCalculator { int add(int i, int j ...

  2. Spring入门第十八课

    Spring AOP AspectJ:Java社区里最完整最流行的AOP框架 在Spring2.0以上的版本中,可以使用基于AspectJ注解或者基于XML配置的AOP 看代码: package lo ...

  3. Spring入门第十六课

    接上一次讲课 先看代码: package logan.spring.study.annotation.repository; public interface UserRepository { voi ...

  4. Spring入门第十五课

    泛型依赖注入 看代码: package logan.spring.study.generic.di; public class BaseRepository<T> { } package ...

  5. Spring入门第十二课

    Bean的配置方法 通过工厂方法(静态工厂方法&实例工厂方法),FactoryBean 通过调用静态工厂方法创建Bean 调用静态工厂方法创建Bean是将对象创建的过程封装到静态方法中,当客户 ...

  6. CTF---Web入门第十四题 忘记密码了

    忘记密码了分值:20 来源: Justatest 难度:中 参与人数:7706人 Get Flag:2232人 答题人数:2386人 解题通过率:94% 找回密码 格式:SimCTF{ } 解题链接: ...

  7. Spring入门第十课

    Spring表达式语言:SpEL Spring表达式语言(简称SpEL)是一个支持运行时查询和操作对象图的强大的表达式语言. 语法类似于EL:SpEL使用#{...}作为定界符,所有在大括号中的字符都 ...

  8. 大数据入门第十四天——Hbase详解(三)hbase基本原理与MR操作Hbase

    一.基本原理 1.hbase的位置 上图描述了Hadoop 2.0生态系统中的各层结构.其中HBase位于结构化存储层,HDFS为HBase提供了高可靠性的底层存储支持, MapReduce为HBas ...

  9. 大数据入门第十四天——Hbase详解(二)基本概念与命令、javaAPI

    一.hbase数据模型 完整的官方文档的翻译,参考:https://www.cnblogs.com/simple-focus/p/6198329.html 1.rowkey 与nosql数据库们一样, ...

随机推荐

  1. EasyNVR H5无插件摄像机直播解决方案前端解析之:videojs初始化的一些样式处理

    初始化完成对videojs样式的调整 由于不同项目的需要,对于加载出来的videojs播放器样式也有不同的需求:我们需要自主的处理一下加载出来的videojs播放器的样式: 默认加载出来的会包含有暂停 ...

  2. 交易准实时预警 kafka topic 主题 异常交易主题 低延迟 event topic alert topic 内存 算法测试

    https://www.ibm.com/developerworks/cn/opensource/os-cn-kafka/index.html 周 明耀2015 年 6 月 10 日发布 示例:网络游 ...

  3. PAT 甲级 1065. A+B and C (64bit) (20) 【大数加法】

    题目链接 https://www.patest.cn/contests/pat-a-practise/1065 思路 因为 a 和 b 都是 在 long long 范围内的 但是 a + b 可能会 ...

  4. python优缺点小结

    优点:  1.语言简洁优美 例如去除了大括号,写法简单,写法更接近于英语,其他语言几十上百行的代码,十来行就能解决,而且还好看 2.跨平台,window.linux.mac通用 3.排行高,社区完善 ...

  5. BZOJ4524 [Cqoi2016]伪光滑数

    BZOJ上的题面很乱,这里有一个题面. 题解: 正解是可持久化可并堆+DP,可惜我不会... 但暴力也可过这道题. 先在不超过N的前提下,在大根堆里加入每个质数的J次方,1<=j, 然后就可以发 ...

  6. Linux bash shell环境变量以及语法规范

    摘自: http://blog.csdn.net/abc_ii/article/details/8762739

  7. centos7下面搭建lnmp环境

    参考大神博客: http://www.linuxzen.com/lnmphuan-jing-da-jian-wan-quan-shou-ce-si-lnmpda-jian-yuan-ma-an-zhu ...

  8. array_2.array_rand

    从数组中随机取出一个或多个单元 <?php $arr = [1, 2, 3]; $rand = array_rand($arr, 2); var_dump($rand);

  9. 机器学习:朴素贝叶斯--python

    今天介绍机器学习中一种基于概率的常见的分类方法,朴素贝叶斯,之前介绍的KNN, decision tree 等方法是一种 hard decision,因为这些分类器的输出只有0 或者 1,朴素贝叶斯方 ...

  10. CentOS 性能监控之nmon

    工具集: Nmon  性能数据收集分析工具Nmon analyser 性能数据分析工具,excel文件nmon_x86_sles10  Nmon在x86_sles10下二进制执行文件 nmon概述 n ...