我想注入默认的Java记录器。但是,Eclipse强调它并指出“没有bean有资格注入注射点[JSR-299§5.2.1]”
如果我仍然部署,则抛出以下异常。为什么它无法注入Java Logger?对于EntityManager也是如此,但对于我自己的UserRepository Bean则不行。
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Logger] with qualifiers [@Default] at injection point [[field]
代码:
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;
}
}
答案 0 :(得分:6)
要注入记录器,您需要一个生成器方法,该方法提供可以注入的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());
}
}
并且EntityManager
需要使用@PersistenceContext(unitName="pscontext")
注入,因为它是使用persistence.xml
中的数据创建的,因此您的EntityManager
必须
@PersistenceContex(unitName="pscontext")
private EntityManager em;