Java 没有 bean 有资格注入注入点 [JSR-299 §5.2.1]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19775901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
No bean is eligible for injection to the injection point [JSR-299 §5.2.1]
提问by feder
I wanted to inject the default Java logger. However, Eclipse underlines it and states "No bean is eligible for injection to the injection point [JSR-299 §5.2.1]"
我想注入默认的 Java 记录器。但是,Eclipse 强调了它并指出“没有 bean 有资格注入注入点 [JSR-299 §5.2.1]”
If I deploy anyway, the following exception is thrown. Why does it fail to inject Java Logger? Same for the EntityManager, but not for my own UserRepository Bean.
如果我仍然部署,则会引发以下异常。为什么注入Java Logger失败?EntityManager 相同,但不适用于我自己的 UserRepository Bean。
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Logger] with qualifiers [@Default] at injection point [[field]
code:
代码:
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import com.terry.webapp.data.UserRepository;
import com.terry.webapp.model.usermgmt.User;
// The @Stateless annotation eliminates the need for manual transaction demarcation
@Stateless
public class LoginService {
@Inject
private Logger log;
@Inject
private EntityManager em;
@Inject
private UserRepository repository;
public User login(User user) {
log.info("login " + user.getUsername());
User rUser = repository.findByCredentials(user.getUsername(), user.getPassword());
return rUser;
}
}
回答by SRy
To inject a logger you need a producer method which gives a Logger
which you can Inject.
要注入记录器,您需要一个生产者方法,该方法提供Logger
您可以注入的 。
import java.util.logging.Logger;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
public class LoggerProduer {
@Produces
public Logger produceLog(InjectionPoint injectionPoint) {
return Logger.getLogger(injectionPoint.getMember().getDeclaringClass()
.getName());
}
}
And EntityManager
needs to be injected using @PersistenceContext(unitName="pscontext")
because it's created using data in your persistence.xml
, so your EntityManager
has to be
并且EntityManager
需要注入 using@PersistenceContext(unitName="pscontext")
因为它是使用您的数据创建的persistence.xml
,所以您EntityManager
必须
@PersistenceContex(unitName="pscontext")
private EntityManager em;