温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring中如何进行搜索Bean类操作

发布时间:2021-10-15 18:07:10 来源:亿速云 阅读:88 作者:柒染 栏目:编程语言

Spring中如何进行搜索Bean类操作,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

一 配置文件

<?xml version="1.0" encoding="GBK"?><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-4.0.xsd   http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-4.0.xsd">   <!-- 自动扫描指定包及其子包下的所有Bean类 -->   <context:component-scan      base-package="org.crazyit.app.service"/></beans>

二 接口

Axe

package org.crazyit.app.service;public interface Axe{   public String chop();}

Person

package org.crazyit.app.service;public interface Person{   public void useAxe();}

三 Bean

Chinese

package org.crazyit.app.service.impl;import org.springframework.stereotype.*;import org.crazyit.app.service.*;@Componentpublic class Chinese  implements Person{  private Axe axe;  // axe的setter方法  public void setAxe(Axe axe)  {    this.axe = axe;  }  // 实现Person接口的useAxe()方法  public void useAxe()  {    System.out.println(axe.chop());  }}

SteelAxe

package org.crazyit.app.service.impl;import org.springframework.stereotype.*;import org.crazyit.app.service.*;@Componentpublic class SteelAxe implements Axe{  public String chop()  {    return "钢斧砍柴真快";  }}

StoneAxe

package org.crazyit.app.service.impl;import org.springframework.stereotype.*;import org.crazyit.app.service.*;@Componentpublic class StoneAxe implements Axe{  public String chop()  {    return "石斧砍柴好慢";  }}

四 测试类

package lee;import org.springframework.context.*;import org.springframework.context.support.*;public class BeanTest{  public static void main(String[] args)  {    // 创建Spring容器    ApplicationContext ctx = new      ClassPathXmlApplicationContext("beans.xml");    // 获取Spring容器中的所有Bean实例的名    System.out.println("--------------" +      java.util.Arrays.toString(ctx.getBeanDefinitionNames()));  }}

五 测试结果

--------------[chinese, steelAxe, stoneAxe, org.springframework.context.annotation.internalConfigurationAnnotationProcessor, org.springframework.context.annotation.internalAutowiredAnnotationProcessor, org.springframework.context.annotation.internalRequiredAnnotationProcessor, org.springframework.context.annotation.internalCommonAnnotationProcessor, org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor, org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor]

关于Spring中如何进行搜索Bean类操作问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI