集册 Java实例教程 从BeanManager中按类型获取实例

从BeanManager中按类型获取实例

欢马劈雪     最近更新时间:2020-01-02 10:19:05

490
从BeanManager中按类型获取实例


import java.lang.annotation.Annotation;
/**
来 自 时   代     Java  公  众  号 - nowjava.com
**/

import java.util.Collection;

import javax.enterprise.context.spi.CreationalContext;

import javax.enterprise.inject.spi.Bean;

import javax.enterprise.inject.spi.BeanManager;


public class Main{

    public final static <T> T getInstanceByType(final BeanManager manager,

            final Class<T> type) {

        try {

            final Bean<?> bean = manager.resolve(manager.getBeans(type));

            CreationalContext<?> ctx = manager

                    .createCreationalContext(bean);

            if (bean != null) {

                return type.cast(manager.getReference(bean, type, ctx));

            }

        } 
展开阅读全文