Spring中的Bean的配置形式
Spring中Bean的配置形式有两种,基于XML文件的方式和基于注解的方式。
1.基于XML文件的方式配置Bean
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<bean id="address" class="com.java.spring.autowire.Address" p:city="上海" p:street="南京路"></bean>
<bean id="car" class="com.java.spring.autowire.Car" p:brand="Audi" p:price="500000.0000"></bean>
<bean id="person" class="com.java.spring.autowire.Person" p:name="Tom" autowire="byType"></bean>
</beans>
像上面这样,在xml文件中使用<bean...></bean>标签设置Bean属性。
2.基于注解的方式配置Bean
把一个Bean加上注解放到IOC容器中,首先需要了解组件扫描。组件扫描(component scanning)是指Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件。特定组件包括:
- @Component: 基本注解, 标识了一个受 Spring 管理的组件
- @Respository: 标识持久层组件
- @Service: 标识服务层(业务层)组件
- @Controller: 标识表现层组件
对于扫描到的组件, Spring 有默认的命名策略: 使用非限定类名, 第一个字母小写. 也可以在注解中通过 value 属性值标识组件的名称。当在组件类上使用了特定的注解之后, 还需要在 Spring 的配置文件中声明 <context:component-scan> :
- base-package 属性指定一个需要扫描的基类包,Spring 容器将会扫描这个基类包里及其子包中的所有类.当需要扫描多个包时, 可以使用逗号分隔;
- 如果仅希望扫描特定的类而非基包下的所有类,可使用 resource-pattern 属性过滤特定的类;
- <context:include-filter> 子节点表示要包含的目标类;
- <context:exclude-filter> 子节点表示要排除在外的目标类;
<context:component-scan> 下可以拥有若干个 <context:include-filter> 和 <context:exclude-filter> 子节点。
2.1 base-package属性
如图,创建如下的项目目录:
分别用TestObject,UserController,UserRepositoryImpl,UserService模拟基本注解,表现层,持久层和业务层。
TestObject.java
package com.java.spring.annotation;
import org.springframework.stereotype.Component;
@Component
public class TestObject { }
UserController.java
package com.java.spring.annotation.controller;
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
public void excute(){
System.out.println("UserController's excute...");
}
}
UserService.java
package com.java.spring.annotation.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public void add(){
System.out.println("UserService's add...");
}
}
UserRepository.java
package com.java.spring.annotation.repository;
public interface UserRepository {
void save();
}
UserRepositoryImpl.java
package com.java.spring.annotation.repository;
import org.springframework.stereotype.Repository;
@Repository("userRepositoryImpl")
public class UserRepositoryImpl implements UserRepository {
@Override
public void save() {
System.out.println("UserRepositoryImpl's save...");
}
}
为Bean添加注解之后还需要在 Spring 的配置文件中声明:
<context:component-scan base-package="com.java.spring.annotation"></context:component-scan>
base-package="com.java.spring.annotation"意思是要扫描annotation包下的所有类。
写一个测试类Main.java:
package com.java.spring.annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java.spring.annotation.controller.UserController;
import com.java.spring.annotation.repository.UserRepositoryImpl;
import com.java.spring.annotation.service.UserService;
public class Main {
public static void main(String[] args){
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-annotation.xml");
UserRepositoryImpl uri=(UserRepositoryImpl) ctx.getBean("userRepositoryImpl");
System.out.println(uri);
TestObject to=(TestObject) ctx.getBean("testObject");
System.out.println(to);
UserService us=(UserService) ctx.getBean("userService");
System.out.println(us);
UserController uc=(UserController) ctx.getBean("userController");
System.out.println(uc);
}
}
运行后输出:
com.java.spring.annotation.repository.UserRepositoryImpl@4671e53b
com.java.spring.annotation.TestObject@2db7a79b
com.java.spring.annotation.service.UserService@6950e31
com.java.spring.annotation.controller.UserController@b7dd107
2.2 <context:include-filter>子节点
子节点表示要包含的目标类。使用<context:include-filter>时要将use-default-filters的值设置为false,默认为true。
比如在beans-annotation.xml中进行配置:
<context:component-scan base-package="com.java.spring.annotation" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
则扫描到的组件只有@Repository("userRepositoryImpl")注解的持久层。
运行后输出:
com.java.spring.annotation.repository.UserRepositoryImpl@e720b71
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'testObject' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:638)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1159)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:282)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
at com.java.spring.annotation.Main.main(Main.java:12)
其他Bean显示未被定义。
2.3 <context:exclude-filter>子节点
子节点表示要排除在外的目标类,如下排除Repository类。
在beans-annotation.xml中进行配置:
<context:component-scan base-package="com.java.spring.annotation">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
Main.java中修改为:
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);
UserService us=(UserService) ctx.getBean("userService");
System.out.println(us);
UserController uc=(UserController) ctx.getBean("userController");
System.out.println(uc);
UserRepositoryImpl uri=(UserRepositoryImpl) ctx.getBean("userRepositoryImpl");
System.out.println(uri);
}
}
运行后输出:
com.java.spring.annotation.TestObject@757942a1
com.java.spring.annotation.service.UserService@4a87761d
com.java.spring.annotation.controller.UserController@66d1af89
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userRepositoryImpl' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:638)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1159)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:282)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
at com.java.spring.annotation.Main.main(Main.java:16)
将Repository排除,则扫描不到被@Repository("userRepositoryImpl")注解的Bean userRepositoryImpl,显示该Bean未被定义。
3.组件装配
<context:component-scan> 元素还会自动注册 AutowiredAnnotationBeanPostProcessor 实例, 该实例可以自动装配具有 @Autowired 和 @Resource 、@Inject注解的属性.
3.1 使用@Autowired自动装配所有Bean
@Autowired 注解自动装配具有兼容类型的单个 Bean属性。
- 构造器, 普通字段(即使是非 public), 一切具有参数的方法都可以应用@Authwired 注解
- 默认情况下, 所有使用 @Authwired 注解的属性都需要被设置. 当 Spring 找不到匹配的 Bean 装配属性时, 会抛出异常, 若某一属性允许不被设置, 可以设置 @Authwired 注解的 required 属性为 false
- 默认情况下, 当 IOC 容器里存在多个类型兼容的 Bean 时, 通过类型的自动装配将无法工作. 此时可以在 @Qualifier 注解里提供 Bean 的名称. Spring 允许对方法的入参标注 @Qualifiter 已指定注入 Bean 的名称
- @Authwired 注解也可以应用在数组类型的属性上, 此时 Spring 将会把所有匹配的 Bean 进行自动装配.
- @Authwired 注解也可以应用在集合属性上, 此时 Spring 读取该集合的类型信息, 然后自动装配所有与之兼容的 Bean.
- @Authwired 注解用在 java.util.Map 上时, 若该 Map 的键值为 String, 那么 Spring 将自动装配与之 Map 值类型兼容的 Bean, 此时 Bean 的名称作为键值.
示例代码:使用Autowired注解
UserController.java
package com.java.spring.annotation.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.java.spring.annotation.service.UserService;
@Controller
public class UserController {
@Autowired
private UserService userservice;
public void excute(){
System.out.println("UserController's excute...");
userservice.add();
}
}
UserService.java
package com.java.spring.annotation.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.java.spring.annotation.repository.UserRepository;
@Service
public class UserService {
@Autowired
private UserRepository userrepository;
public void add(){
System.out.println("UserService's add...");
userrepository.save();
}
}
UserRepositoryImpl.java
package com.java.spring.annotation.repository;
import org.springframework.stereotype.Repository;
@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository {
@Override
public void save() {
System.out.println("UserRepository's save...");
}
}
在主方法中测试:
public class Main {
public static void main(String[] args){
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-annotation.xml");
UserController uc=(UserController) ctx.getBean("userController");
System.out.println(uc);
uc.excute();
}
主方法中调用uc.excute();指向 UserController.java 中的excute()方法,先执行System.out.println("UserController's excute...");,再调用userservice.add();方法,此时需要使用Autowired注解UserService这个Bean,否则相当于UserService这个Bean未配置到IOC容器中去,出错;userservice.add();方法指向 UserService.java中的add()方法,先执行System.out.println("UserService's add...");,再调用userrepository.save();方法,同理需要注解Bean,可以看到在UserRepositoryImpl.java中使用注解@Repository("userRepository")。
3.2 @Resource 和 @Inject
Spring 还支持 @Resource 和 @Inject 注解,这两个注解和 @Autowired 注解的功用类似。@Resource 注解要求提供一个 Bean 名称的属性,若该属性为空,则自动采用标注处的变量或方法名作为 Bean 的名称。@Inject 和 @Autowired 注解一样也是按类型匹配注入的 Bean, 但没有 reqired 属性。建议使用 @Autowired 注解。
4.泛型依赖注入
Spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用。
BaseService<T>中引用了BaseRepository<T>,UserService为BaseService<T>的实现类,UserRepository为BaseRepository<T>的实现类,那么UserService和BaseService之间会自动地建立引用关系。
示例代码:
BaseService.java
package com.java.spring.generic.di; import org.springframework.beans.factory.annotation.Autowired; public class BaseService<T>{
@Autowired
private BaseRepository<T> repository;
public void add(){
System.out.println("add...");
System.out.println(repository);
}
}
BaseRepository.java
package com.java.spring.generic.di; public class BaseRepository<T> { }
User.java
package com.java.spring.generic.di;
public class User {
public User() {
}
}
UserService.java
package com.java.spring.generic.di;
import org.springframework.stereotype.Service;
@Service
public class UserService extends BaseService<User> { }
UserRepository.java
package com.java.spring.generic.di;
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository extends BaseRepository{
public UserRepository() { }
}
在beans-generic-di.xml中进行配置:
<context:component-scan base-package="com.java.spring.generic.di"></context:component-scan>
在主方法中进行测试:
public static void main(String[] args){
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-generic-di.xml");
UserService userService=(UserService) ctx.getBean("userService");
System.out.println(userService);
userService.add();
}
运行输出:
com.java.spring.generic.di.UserService@8e24743
add...
com.java.spring.generic.di.UserRepository@74a10858
在以上的代码中,BaseService中引用了BaseReponsitory,并且在BaseService的add方法中调用了BaseReponsitory的add方法。在他们的子类中,继承了这种关系。因此我们在测试方法中调用userService.add(); 也是可以成功地调用UserReponsitory中的add方法。
wx搜索“程序员考拉”,专注java领域,一个伴你成长的公众号!
Spring中的Bean的配置形式的更多相关文章
- 【Spring】Spring中的Bean - 1、Baen配置
Bean配置 简单记录-Java EE企业级应用开发教程(Spring+Spring MVC+MyBatis)-Spring中的Bean 什么是Spring中的Bean? Spring可以被看作是一个 ...
- 第2章 Spring中的Bean
2.1 Bean的配置 Bean本质是Java中的类.Spring可以被看做一个大型工厂,这个工厂的作用就是生产和管理Spring容器zho中的Bean.想在项目中使用这个工厂,就需要对Spring的 ...
- spring(四):spring中给bean的属性赋值
spring中给bean的属性赋值 xml文件properties标签设置 <bean id="student" class="com.enjoy.study.ca ...
- 【Spring】Spring中的Bean - 5、Bean的装配方式(XML、注解(Annotation)、自动装配)
Bean的装配方式 简单记录-Java EE企业级应用开发教程(Spring+Spring MVC+MyBatis)-Spring中的Bean 文章目录 Bean的装配方式 基于XML的装配 基于注解 ...
- Spring中管理Bean以及解析XML
Spring是分层的轻量级框架 以IoC(Inverse of Control 反转控制)和AOP(Aspect Oriented Programming 面向切面编程)为核心 应用Spring的好处 ...
- Spring中添加新的配置表,并对新的配置表进行处理
实习过程中boss交代的任务(以下出现的代码以及数据只给出小部分,提供一个思路) 目的:Spring中添加新的配置表,并对新的配置表进行处理:替换的新的配置表要友好,同时保证替换前后功能不能发生变化. ...
- 1.2(Spring学习笔记)Spring中的Bean
一.<Bean>的属性及子元素 在1.1中我们对<Bean>有了初步的认识,了解了一些基本用法. 现在我们进一步理解<Bean>属性及子元素. 我们先来看下< ...
- spring扩展点之二:spring中关于bean初始化、销毁等使用汇总,ApplicationContextAware将ApplicationContext注入
<spring扩展点之二:spring中关于bean初始化.销毁等使用汇总,ApplicationContextAware将ApplicationContext注入> <spring ...
- Spring 中的bean 是线程安全的吗?
结论: 不是线程安全的 Spring容器中的Bean是否线程安全,容器本身并没有提供Bean的线程安全策略,因此可以说Spring容器中的Bean本身不具备线程安全的特性,但是具体还是要结合具体sco ...
随机推荐
- 全球第一开源云ERP Odoo操作手册 模块安装和界面汉化指南
之前介绍了odoo的安装和初始设置以及数据库,下面来介绍odoo的模块安装和界面汉化. 1.4 模块安装和界面汉化 Odoo 的功能包含在不同的模块中, 刚创建的数据库除 Odoo 的核心模块外, 其 ...
- Delphi - 10.1编译OSX10.12程序遇到错误解决了!
昨天,尝试Delphi的跨平台开发功能,在windows10下,做了一个控制台程序,发布目标平台是OSX10.12,中间配置过程都非常顺利,没有任何错误,但是当编译运行时候出现下面错误: [dccos ...
- hdu4462--曼哈顿距离
题目大意:有N*N个点的田野,然后有k个点是用来放稻草人的,每个稻草人对周围满足曼哈顿距离的庄稼有保护作用 问最小的稻草人的个数能够保护所有庄稼,如果不能保护则输出-1 注意的地方: 1.放稻草人的点 ...
- IdentityServer4登陆中心
1. 使用Vsual Studio Code 终端执行 dotnet new webapi --name IdentityServerSample 命令创建一个webapi 的 IdentitySer ...
- class字节码结构(二)(访问标志、类索引、父类索引、接口索引集合)
<Java虚拟机原理图解>1.3.class文件中的访问标志.类索引.父类索引.接口索引集合 字节码总体结构: 访问标志(access_flags)能够表示什么? 访问标志(access_ ...
- 【bzoj3489】 A simple rmq problem k-d树
由于某些原因,我先打了一个错误的树套树,后来打起了$k-d$.接着因不明原因在思路上被卡了很久,在今天中午蹲坑时恍然大悟...... 对于一个数字$a_i$,我们可以用一组三维坐标$(i,pre,nx ...
- POJ 1169
#include<iostream> #include<algorithm> #include<vector> #include<set> #defin ...
- 剑指offer三十八之二叉树的深度
一.题目 输入一棵二叉树,求该树的深度.从根结点到叶结点依次经过的结点(含根.叶结点)形成树的一条路径,最长路径的长度为树的深度. 二.思路 递归,详见代码. 三.代码 public class So ...
- (转)python高级:列表解析和生成表达式
一.语法糖的概念 “糖”,可以理解为简单.简洁,“语法糖”使我们可以更加简洁.快速的实现这些功能. 只是Python解释器会把这些特定格式的语法翻译成原本那样复杂的代码逻辑 我们使用的语法糖有: if ...
- 漫谈NIO(2)之Java的NIO
1.前言 上章提到过Java的NIO采取的是多路IO复用模式,其衍生出来的模型就是Reactor模型.多路IO复用有两种方式,一种是select/poll,另一种是epoll.在windows系统上使 ...