05_IOC容器装配Bean(注解方式)
IOC容器装配Bean(注解方式)
1.使用注解方式进行Bean注册
xml 方式: <bean id="" class="">
spring2.5版本 提供一组注解,完成Bean注册
* @Component 描述Spring框架中Bean
导入jar 和 xml方式开发是相同的
第一步 编写Class,在声明上 添加 @Component
/*** 使用Spring2.5注解 注册Bean*/@Component("helloService")// <bean id="helloService" class="...." />publicclassHelloService{publicvoid sayHello(){System.out.println("hello, spring annotation!");}}
第二步 编写applicationContext.xml 通知Spring注解类所在包
* 需要引入 context 名称空间
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- 配置 注解Bean 所在包 --><context:annotation-config/><context:component-scanbase-package="cn.itcast.spring.a_beandefinition"></context:component-scan></beans>
publicclassSpringTest{@Test// 测试 注解Bean 注册publicvoid demo1(){ApplicationContext applicationContext =newClassPathXmlApplicationContext("applicationContext.xml");- //bean的名称来自@Component("helloService")
HelloService helloService =(HelloService) applicationContext.getBean("helloService");helloService.sayHello();}}
* @Repository 用于对DAO实现类进行标注 (持久层)
* @Service 用于对Service实现类进行标注 (业务层)
* @Controller 用于对Controller实现类进行标注 (表现层)
2.属性依赖注入
1) 简单属性的注入 通过 @Value注解完成,不需要提供setter方法
@Service("userService")public class UserService {// 注入name属性@Value("itcast")private String name;}
2) 复杂属性注入,通过@Autowired注解 完成Bean自动装配
@Autowired 默认按照类型进行注入
/*** 用户操作数据层*/@Repository("userDAO")publicclassUserDAO{}
/*** 用户业务层*/@Service("userService")publicclassUserService{// 注入name属性@Value("itcast")// 简单属性privateString name;- //@Autowired默认按照类型
@AutowiredprivateUserDAO userDAO;@OverridepublicString toString(){return"UserService [name="+ name +", userDAO="+ userDAO +"]";}}
@Autowired注解 结合 @Qualifer注解按照名称注入
@Service("userService")public class UserService {@Autowired@Qualifier("uDAO")// 复杂对象private UserDAO userDAO;}
@Repository("uDAO")public class UserDAO {}
3) 使用@Resource注解 完成复杂对象Bean装配
@Resource和@Autowired注解功能相似
@Autowired@Qualifer("userDAO")private UserDAO userDAO ;
@Resource(name="userDAO")private UserDAO userDAO ;
3.Bean其它属性设置
1) 指定Bean的初始化方法和销毁方法(注解) <bean init-method="" destroy-method="" />
@PostConstruct 作用 init-method
@PreDestroy 作用 destroy-method
@Component("lifeBean")publicclassLifeCycleBean{@PostConstructpublicvoid setup(){System.out.println("初始化...");}@PreDestroypublicvoid teardown(){System.out.println("销毁...");}}
@Test// 测试初始化和销毁publicvoid demo1(){ClassPathXmlApplicationContext applicationContext =newClassPathXmlApplicationContext("applicationContext.xml");LifeCycleBean lifeCycleBean =(LifeCycleBean) applicationContext.getBean("lifeBean");System.out.println(lifeCycleBean);// 销毁方法执行,必须销毁ApplicationContextapplicationContext.close();}
2) Bean的作用范围 <bean scope="" />
@Scope 注解 ,默认作用域 singleton 单例
@Component("scopeBean")// 如果没有指定scope 是 singleton 单例@Scope("prototype")publicclassScopeBean{}
@Test// 测试Bean 范围publicvoid demo2(){ApplicationContext applicationContext =newClassPathXmlApplicationContext("applicationContext.xml");ScopeBean scopeBean =(ScopeBean) applicationContext.getBean("scopeBean");System.out.println(scopeBean);ScopeBean scopeBean2 =(ScopeBean) applicationContext.getBean("scopeBean");System.out.println(scopeBean2);}
4.Spring3.0 提供 注册Bean的注解
@Configuration 指定POJO类为Spring提供Bean定义信息
@Bean 提供一个Bean定义信息
先定义2个JavaBean:
// 轿车publicclassCar{privateString name;privatedouble price;publicString getName(){return name;}publicvoid setName(String name){this.name = name;}publicdouble getPrice(){return price;}publicvoid setPrice(double price){this.price = price;}@OverridepublicString toString(){return"Car [name="+ name +", price="+ price +"]";}}
// 商品publicclassProduct{privateString pname;privateint pnum;publicString getPname(){return pname;}publicvoid setPname(String pname){this.pname = pname;}publicint getPnum(){return pnum;}publicvoid setPnum(int pnum){this.pnum = pnum;}@OverridepublicString toString(){return"Product [pname="+ pname +", pnum="+ pnum +"]";}}
/*** 配置Bean (工厂)*/@ConfigurationpublicclassBeanConfig{// 提供两个方法 获得Car和Product对象@Bean(name ="car")//方法名称随意publicCar initCar(){Car car =newCar();car.setName("大众");car.setPrice(10000);return car;}@Bean(name ="product")publicProduct showProduct(){Product product =newProduct();product.setPname("空调");product.setPnum(100);return product;}}
@Test// 获得配置Bean 工厂创建Bean对象publicvoid demo(){ApplicationContext applicationContext =newClassPathXmlApplicationContext("applicationContext.xml");Car car =(Car) applicationContext.getBean("car");System.out.println(car);Product product =(Product) applicationContext.getBean("product");System.out.println(product);}
5.xml和注解混合使用
很多企业开发者 还是采用xml作为主流配置
* Bean 注册 通过XML完成
* 注入使用 @Autowired 注解完成
将2个Dao注入到Service
// 客户DAOpublicclassCustomerDAO{}
// 订单DAOpublicclassOrderDAO{}
// 客户ServicepublicclassCustomerService{// xml注入privateCustomerDAO customerDAO;publicvoid setCustomerDAO(CustomerDAO customerDAO){this.customerDAO = customerDAO;}@OverridepublicString toString(){return"CustomerService [orderDAO="+ orderDAO +", customerDAO="+ customerDAO +"]";}}
<bean id="customerDAO"class="cn.itcast.spring.e_xmluseannotaion.CustomerDAO"></bean><bean id="orderDAO" class="cn.itcast.spring.e_xmluseannotaion.OrderDAO"></bean><!--将DAO 注入Service--><bean id="customerService"class="cn.itcast.spring.e_xmluseannotaion.CustomerService"><property name="customerDAO" ref="customerDAO"></property></bean>
@Test// 完成 DAO 注入到Service测试publicvoid demo(){ApplicationContext applicationContext =newClassPathXmlApplicationContext("applicationContext2.xml");CustomerService customerService =(CustomerService) applicationContext.getBean("customerService");System.out.println(customerService);}
// 客户ServicepublicclassCustomerService{// 注解注入@AutowiredprivateOrderDAO orderDAO;// xml注入privateCustomerDAO customerDAO;publicvoid setCustomerDAO(CustomerDAO customerDAO){this.customerDAO = customerDAO;}@OverridepublicString toString(){return"CustomerService [orderDAO="+ orderDAO +", customerDAO="+ customerDAO +"]";}}
<context:annotation-config/> 启用四个注解 使@Resource、@ PostConstruct、@ PreDestroy、@Autowired注解生效
结论 :
1、 xml配置 和 注解配置 效果完全相同
2、 如果Bean 来自第三方(源码无法改动), 必须使用xml
3、 Spring3.0 Bean注册方式, 使用比较少,主要用于Bean 构造逻辑及其复杂
05_IOC容器装配Bean(注解方式)的更多相关文章
- 04_IOC容器装配Bean(xml方式)
IOC容器装配Bean(xml方式) 1.Spring 提供配置Bean三种实例化方式 1)使用类构造器实例化(默认无参数) <bean id="bean1" class=& ...
- Spring框架(3)---IOC装配Bean(注解方式)
IOC装配Bean(注解方式) 上面一遍文章讲了通过xml来装配Bean,那么这篇来讲注解方式来讲装配Bean对象 注解方式需要在原先的基础上重新配置环境: (1)Component标签举例 1:导入 ...
- spring IOC装配Bean(注解方式)
1 Spring的注解装配Bean (1) Spring2.5 引入使用注解去定义Bean @Component 描述Spring框架中Bean (2) Spring的框架中提供了与@Componen ...
- Spring 框架 详解 (四)------IOC装配Bean(注解方式)
Spring的注解装配Bean Spring2.5 引入使用注解去定义Bean @Component 描述Spring框架中Bean Spring的框架中提供了与@Component注解等效的三个注 ...
- Spring IOC 一——容器装配Bean的简单使用
下文:SpringIOC 二-- 容器 和 Bean的深入理解 写在前面 这篇文章去年写的,缘起于去年某段时间被领导临时"抓壮丁"般的叫过去做java开发,然后在网上找了一个 Sp ...
- spring IOC容器实例化Bean的方式与RequestContextListener应用
spring IOC容器实例化Bean的方式有: singleton 在spring IOC容器中仅存在一个Bean实例,Bean以单实例的方式存在. prototype 每次从容器中调用Bean时, ...
- Spring容器装配Bean的三种方式
欢迎查看Java开发之上帝之眼系列教程,如果您正在为Java后端庞大的体系所困扰,如果您正在为各种繁出不穷的技术和各种框架所迷茫,那么本系列文章将带您窥探Java庞大的体系.本系列教程希望您能站在上帝 ...
- Spring容器、BeanFactory和ApplicationContext,及3种装配Bean的方式
目录 一. spring容器理解 二. BeanFactory和ApplicationContext之间的关系 三. BeanFactory详情介绍 四.ApplicationContext介绍 五. ...
- spring实战二之Bean的自动装配(非注解方式)
Bean的自动装配 自动装配(autowiring)有助于减少甚至消除配置<property>元素和<constructor-arg>元素,让Spring自动识别如何装配Bea ...
随机推荐
- UIViewController卸载过程(ios6.0以后)
在ios6.0以后,废除了viewWillUnload方法和viewDidUnload方法. 在ios6以后,当收到didReceiveMemoryWarning消息调用之后,程序会自动调用didRe ...
- ImagXpress中如何修改Alpha通道方法汇总
ImagXpress支持处理Alpha通道信息来管理图像的透明度,Alpha通道支持PNG ,TARGA和TIFF文件,同时还支持BMP和ICO文件.如果说保存的图像样式不支持Alpha通道,就将会丢 ...
- 爱普生 RS330 打印机墨水连供装置墨盒吸墨复位方法
芯片复位方法: 先按充墨键(墨水灯按键),一下一下按,把墨车按停到右侧换墨盒的位置为止(就是右侧框框正中位置), 全程带电操作,停到换墨盒的位置后再按住芯片复位键(墨盒芯片上面白色的小按键)5秒以上再 ...
- 【python cookbook】【字符串与文本】6.以不区分大小写的方式对文本做查找和替换
问题:以不区分大小写的方式对文本做查找和替换 解决方法:使用re模块,并对各种操作都添加上re.IGNORECASE标记 text='UPPER PYTHON,lower python,Mixed P ...
- Java锁的种类
转载自:---->http://ifeve.com/java_lock_see/ Java锁的种类以及辨析锁作为并发共享数据,保证一致性的工具,在JAVA平台有多种实现(如 synchroniz ...
- Java、JVM和操作系统之间的关系,写给新人,
来张图:这个帖子写给新人的,老玩家就直接无视他,因为这个完完全全是白话基础原理. 解释:上面的图是从上往下依次调用的关系. 操作系统(Windows/Linux)管理硬件,让硬件能够正常.合理的运行, ...
- 给NIOS II CPU添加一颗澎湃的心——sysclk的使用
给NIOS II CPU添加一颗澎湃的心——系统时钟的使用 本实验介绍如何在Qsys中添加一个定时器作为NIOS II的心跳定时器,并在NIOS II中软件编程使用该定时器. 将上一个实验watchd ...
- PyChram使用技巧总结
1.1 下载 官网1.2 汉化 1.3 添加或者修改文件模板 File->settings->Editor->File and Code Templates->Python S ...
- discuz阅读权限的设置作用
为什么要有阅读权限?偶想很多新手有这个疑问吧,所以特开此帖说明下. 阅读权限的设置是帖子作者为了部分限制帖子的读者群.虽然网上发帖重在分享,但帖子(尤其精华帖子)是作者花时间和经历而写成的,不加阅读权 ...
- 1. python中的随机函数
本系列不会对python语法,理论作详细说明:所以不是一个学习教材:详细查考Vamei 大神:通俗易懂:是一个很好(基础-中级-高级)的学习教程.而这里只是我一个学习python的某些专题的 ...