spring|Spring 基于注解(annotation)的配置之@Qualifier注解
使用@Qualifier可以分别为同样类型的Bean分别注入不同的依赖值 。 看个例子:
Student.java:
package com.sappublic class Student { private Integer age private String name public void setAge(Integer age) { this.age = age }public Integer getAge() { return age } public void setName(String name) { this.name = name }public String getName() { return name }}
Profile:
package com.sapimport org.springframework.beans.factory.annotation.Autowiredimport org.springframework.beans.factory.annotation.Qualifierpublic class Profile { @Autowired @Qualifier("student1") private Student student public Profile(){ System.out.println("Inside Profile constructor." ) } public void printAge() { System.out.println("Age : " + student.getAge() ) } public void printName() { System.out.println("Name : " + student.getName() ) }}
Main.app:
package com.sapimport org.springframework.context.ApplicationContextimport org.springframework.context.support.ClassPathXmlApplicationContextpublic class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml") Profile profile = (Profile) context.getBean("profile") profile.printAge() profile.printName() }}
Beans.xml:
<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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/><bean id="profile" class="com.sap.Profile"> bean>
<bean id="student1" class="com.sap.Student"> <property name="name" value="http://news.hoteastday.com/a/Zara" /> <property name="age" value="http://news.hoteastday.com/a/11"/> bean><bean id="student2" class="com.sap.Student"> <property name="name" value="http://news.hoteastday.com/a/Nuha" /> <property name="age" value="http://news.hoteastday.com/a/2"/> bean>beans> 输出:
如果把profile类里的id改成student2:
本文插图
【spring|Spring 基于注解(annotation)的配置之@Qualifier注解】
输出:
本文插图
声明:转载此文是出于传递更多信息之目的 。 若有来源标注错误或侵犯了您的合法权益 , 请作者持权属证明与本网联系 , 我们将及时更正、删除 , 谢谢 。邮箱地址:newmedia@xxcb.cn
推荐阅读
- spring框架之注解的使用
- Spring扩展接口Aware家族
- 中大唯信-唯信计算|JMC | 基于网络的方法在药物研发中的应用
- 照相机|基于Excel和Java自动化工作流程实例:发票生成器
- 时间同步|科研人员提出一种基于仅接收端的三步式水下传感网络时间同步协议
- Lucid|Lucid Motors计划推纯电SUV 将与Lucid Air基于同一平台打造
- 技术编程|spring cloud- 第一回 初识
- 吉利PREFACE官图发布 基于CMA架构打造/搭载2.0T发动机
- 发布会预告丨专家大咖解读国内首个基于攻防实战的零信任白皮书
- 基于再生价值的城市废弃铁路沿线空间重构策略——亚特兰大环线对我国废弃铁路再生的启示
