简体   繁体   English

如何访问Spring Bean名称?

[英]How To Access Spring Bean name?

@Named("myUniqueName") 
public class ReportDashboardDao implements DashboardDAO{ 
//STUFF 
}

how can i access the string inside @Named tag when i am injecting DashboardDAO like this : 当我像这样注入DashboardDAO时,如何访问@Named标记内的字符串:

@Named
public class DshboardDaoConsumer(){

@Inject List<DashboardDAO> dashboardDAO;
//STUFF
} 

Use a Map instead 改用地图

@Inject 
Map<String, DashboardDao> dashBoardDaos;

This will inject a Map with bean names as keys and daos as values. 这将插入一个以bean名称作为键,以daos作为值的Map

Of course, you could also read the annotation value from class instances. 当然,您也可以从类实例中读取注释值。

You can't. 你不能 You're injecting by type. 您正在按类型进行注入。 After injection has been done, Spring does not leave behind any relation between the bean's object and the bean's name. 注入完成后,Spring不会在Bean的对象和Bean的名称之间留下任何关系。

You might want to check out ApplicationContext#getBeanNamesByType() depending on what you want to do. 您可能要根据要执行的操作检出ApplicationContext#getBeanNamesByType()

By implementing BeanNameAware . 通过实现BeanNameAware

@Named("myUniqueName") 
public class ReportDashboardDao implements DashboardDAO, BeanNameAware{ 
      //STUFF 

     private String beanName;

     @Override 
     public Void setBeanName(String beanName) {
        this.beanName = beanName;
     } 

}

So that Spring can inject the beanName into the bean. 这样Spring可以将beanName注入bean中。 If you add a public String getBeanName(); 如果添加公共String getBeanName(); in your DashboardDAO interface, DashboardDaoConsumer will be able to obtain it. 在您的DashboardDAO界面中, DashboardDaoConsumer将能够获取它。

In this particular case, Spring will inject the name you specified in the annotation. 在这种情况下,Spring将注入您在注释中指定的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM