How to inject beans with AspectJ and CDI - cdi

I've coded this aspect:
#Aspect
public class LoggingCacheAspect {
#Pointcut("call * javax.cache.integration.CacheLoader.load(*)")
void cacheLoadCalls() {};
#Before("cacheLoadCalls")
public void beforeCacheCalls() {}
}
Also, I'm using CDI, and I'm looking forward to figure out how to inject a bean into this aspect.
I guess that adding #Inject annotation will not be enought.
Is it possible?
How could I get it?

You need to use an interceptor instead of the aspect
Here is an example:
#InterceptorBinding
#Target({TYPE, METHOD })
#Retention(RUNTIME)
public #interface CacheLog{
}
#Interceptor
#CacheLog
public class CacheLogInterceptor implements Serializable {
private static final long serialVersionUID = 1L;
#Inject
private YourBean yourBean;
#AroundInvoke
public Object cacheLogMethodCall(InvocationContext ctx) throws Exception {
//#Before
yourBean.method();
...
return ctx.proceed();
}
}
#CacheLog
public void cacheLoadCalls() {
...
...
}

Related

CDI Injected Bean from super class has null fields in child

I'm pretty new to the general procedure of bean injection. I've googled a lot but haven't found a solution to my problem.
Additional Information
Running Wildfly 9.0.1 final
EJB Vers. : 3.1
CDI Vers. : 2.2.16 (SP1)
JSF Vers. : 2.2
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.inject.Named;
#Named
#ViewScoped
public class UserEmailSettingsBean extends UserModuleSettingsBean {
private List<String> store;
private List<String> selectedStore;
//getters and setters, some fancy stuff...
#Override
public boolean saveProperties() {
LOG.info("Save called");
LOG.info(selectedStore.toString());
LOG.info(store.toString());
for(String prop : store) {
getProperties().setProperty(prop, String.valueOf(false));
}
for(String selectedProp : selectedStore){
LOG.info("selected: " + selectedProp + ":" + getProperties().getProperty(selectedProp) + " -> true");
getProperties().setProperty(selectedProp, String.valueOf(true));
}
super.saveProperties();
return true;
}
}
2nd Class:
public abstract class UserModuleSettingsBean implements ModuleSettings {
private static final long serialVersionUID = 459417872482285085L;
protected abstract List<String> getPropertiesName();
#Inject
private SettingsRepository settingsRepository;
#Inject
private SettingsService settingsService;
private Properties properties = new Properties();
#Override
public boolean saveProperties() {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
settingsService.store(getProperties(), username);
return (true);
}
}
The problem is, that the settingsService is constructed, however its field "settingsRepository" is null in my child class.
On the call of my save method from UserEmailSettings, getProperties().setProperty() is called with the right values, however its never stored, as the settingsRepository is null. I believe that is due to a wrong Injection for some reason.
Let me know if I need to provide more information ☺
Here is the needed part of SettingsRepository:
#Stateless
#TransactionAttribute(TransactionAttributeType.SUPPORTS)
public class SettingsService implements Serializable {
private static final long serialVersionUID = 1695882717866085259L;
#Inject
SettingsRepository settingsRepository;
//...
}
And here the information SettingsRepository
#Stateless
public class SettingsRepository extends AbstractBaseRepository<Settings, Long> {
/**
* Instantiates a new settings repository.
*/
public SettingsRepository() {
super(Settings.class);
}
}
wanted to say my problem was that I didn't called an init() function on the settingsService to create the propertys, so getProperties was empty

Resource injection issue JSF 2.2

I try to achieve resource injection for a long time but couldn't succeeded.
I use JSF 2.2, JDK 1.7. And my ide is eclipse luna.
I have a session scoped bean called UserBean and view scoped bean called SettingsBean.
I set them in faces-config.xml UserBean as session scoped and SettingsBean as view scoped with their bean name "settingsBean" and "userBean"
public class SettingsBean implements Serializable {
private static final long serialVersionUID = 1L;
#Inject // I also tried #ManagedProperty but didn't work
private UserBean userBean;
#PostConstruct
public void init(){
System.out.println(userBean.getUser().getFullName());
}
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
}
The problem is I get userBean as null. What is the problem here?
Thanks for help.
I removed ManagedBean and ViewScoped definitions in faces-config.xml for settingsBean and added them in SettingsBean.java file manually.
And added this also:
#ManagedProperty(value="#{userBean}")
private UserBean userBean;
So finally, it works:
#ManagedBean
#ViewScoped
public class SettingsBean implements Serializable{
private static final long serialVersionUID = 1L;
#ManagedProperty(value="#{userBean}")
private UserBean userBean;
//...
#PostConstruct
public void init(){
System.out.println(userBean.getUser().getFullName());
}
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
}

GlassFish ManagedBeanCreationException and NullPointerException

I have written an EJB and a dynamic web project Eclipse on GlassFish server. I used DAO , Facade and JPA. Normally I am calling a method from my service it is giving these errors ;
kitapOduncVerme.xhtml]com.sun.faces.mgbean.ManagedBeanCreationException
PWC1406: Servlet.service() for servlet Faces Servlet threw exceptionjava.lang.NullPointerException
at com.mesutemre.kitapislemleri.KitapOduncVermeBean.initList(KitapOduncVermeBean.java:47)
at com.mesutemre.kitapislemleri.KitapOduncVermeBean.initialize(KitapOduncVermeBean.java:43)
My codes are below;
#ManagedBean(name = "oduncKitapVerBean")
#ViewScoped
public class KitapOduncVermeBean implements Serializable{
private static final long serialVersionUID = 1L;
private List<Kitaplar> entityList = new ArrayList<Kitaplar>();
private Kitaplar selectedEntity;
private Kitaplar entity;
private String kullaniciadi;
private KitaplarFacade service;
public KitapOduncVermeBean() {
entity = new Kitaplar();
selectedEntity = new Kitaplar();
}
#PostConstruct
public void initialize(){
HttpSession session = Util.getSession();
kullaniciadi = Util.getUserName();
initList();
}
private void initList(){
entityList = service.findAllKitaplar();
}
DaoImpl
#SuppressWarnings("unchecked")
public List<Kitaplar> findAllKitaplar(){
return em.createNamedQuery("tumkitaplarigetir").getResultList();
}
Dao
#Stateless
#LocalBean
public class KitaplarDAO extends KitaplarDaoImpl<Kitaplar> implements Serializable{
private static final long serialVersionUID = 1L;
#Override
public List<Kitaplar> findAllKitaplar() {
return super.findAllKitaplar();
}
FacadeImpl
#Stateless
#LocalBean
public class KitaplarFacadeImpl implements KitaplarFacade,Serializable {
private static final long serialVersionUID = 1L;
#EJB
KitaplarDAO kitapDao;
#Override
public List<Kitaplar> findAllKitaplar() {
return kitapDao.findAllKitaplar();
}
}
Facade
#Local
public interface KitaplarFacade {
public abstract List<Kitaplar> findAllKitaplar();
}
I can't see any problem in this codes? But Why am I getting that errors?
ManagedBeanCrearionException is simply wrapping and rethrowing the NullPointerException, that is very easy to debug: you have a null variable at the exact line that appears in the stack trace.
In KitapOduncVermeBean class, you are declaring service property, but you are not initializing it, therefore it's null when invoked in initList() method. Since it's an EJB, annotate it as such and the EJB container will instantiate it automatically:
#EJB
private KitaplarFacade service;
Unrelated to the concrete problem, your code is too complicated: with EJB 3.x, in most web applications, you don't need EJBs to implement or expose interfaces.

Injection of ManagedBean to another bean is failed

I tried to inject a Managed Bean to another bean, but failed. That is the first bean:
#ManagedBean(name = "sucBean")
#SessionScoped
public class SucBean implements Serializable {
private static final long serialVersionUID = 1L;
private MapModel advancedModel;
private MapModel advancedModel2;
private Marker marker;
private Suc suc;
private List<Suc> sucDefteri;
private List<Suc> searchResult;
private Suc[] selectedSuc;
private SucService sucService;
private String aramaKriteri;
private String arananKelime;
private SucDataModel sucModel;
// other getters/setters methods
When I run the web application, I'm getting the
Caused by: java.lang.NullPointerException
at org.primefaces.component.chart.CartesianChart.getCategories(CartesianChart.java:32)
at org.primefaces.component.chart.bar.BarChartRenderer.encodeData(BarChartRenderer.java:121)
at org.primefaces.component.chart.bar.BarChartRenderer.encodeScript(BarChartRenderer.java:51)
at org.primefaces.component.chart.bar.BarChartRenderer.encodeEnd(BarChartRenderer.java:36)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1786)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1782)
The second bean is following:
#ManagedBean(name="chartBean")
#SessionScoped
public class ChartBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private CartesianChartModel categoryModel;
#ManagedProperty("#{sucBean}")
private SucBean sucBean;
private int[] sucSayilari=new int[9];
public ChartBean()
{
createCategoryModel();
}
I think this is the problem:
public ChartBean()
{
createCategoryModel();
}
Your dependencies are not set at this point because the JSF implementation first instantiates your bean (and that means that the constructor must finish) and then injects its dependencies, so if you are using the injected bean in createCategoryModel() it will be a null reference.
If you need to do something with your bean AFTER dependencies are set use a method anotated with #PostConstruct:
public ChartBean(){
}
#PostConstruct
public void init(){
createCategoryModel();
}

CDI not working when Injecting in Generics class - Java

I'm having problems with CDI on tomcat. That's some relevant part of my code:
public class JPAUtil {
private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("unit");
#Produces #RequestScoped
public static EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void close(#Disposes EntityManager em) {
em.close();
}
}
My DAO Class:
public class DAO<T> implements Serializable{
private final Class<T> classe;
#Inject
protected EntityManager em;
public DAO(Class<T> classe) {
this.classe = classe;
}
}
and a child class:
public class UserDao extends DAO<User> implements Serializable{
public UserDao() {
super(User.class);
}
}
Because of the Generics, I used a producer for the DAO class:
public class DAOFactory {
#Produces
#SuppressWarnings({ "rawtypes", "unchecked" })
public DAO createDAO(InjectionPoint injectionPoint) {
ParameterizedType type = (ParameterizedType) injectionPoint.getType();
Class classe = (Class) type.getActualTypeArguments()[0];
return new DAO(classe);
}
}
In this example:
public class Test {
#Inject UserDAO userDAO;
#Inject DAO<User> dao;
}
When I try to use the UserDAO class, everything works fine, but when I use the DAO, the EntityManager remains null. Anyone have any idea?
In DAOFactory you instantiate the DAO with new operator, if you do so, CDI has no chance to inject dependencies in the DAO instance.
While in UserDAO CDI manages the entity manager injection.
So in DAOFactory you should set manually the entity manager in the newly created DAO instance.

Resources