I created a bean called ProxyBean that contains a method called getProxies(). I’m trying to call this method from another java-class by injecting the bean. However, I get an Exception that says that the injected object is null. Is there any solutin?
Exception:
ProxyBean:
package com.company.tenderflow.managedBeans;
@Component(ProxyBean.NAME)
public class ProxyBean {
@Inject
private Persistence persistence;
@Inject
protected Authentication authentication;
public static final String NAME = "tenderflow_ProxyBean";
public void createTimer(){
TimerTask task = new CheckTask();
java.util.Timer timer = new java.util.Timer();
timer.schedule(task, 0, 86400000); //24h
}
public ArrayList<Proxy> getProxies(){
ArrayList<Proxy> proxies = new ArrayList<>();
int i=0;
Transaction tx = persistence.createTransaction();
try {
EntityManager em = persistence.getEntityManager();
Query query = em.createQuery(
"select e from tenderflow$Proxy e where e.state=true");
List list = query.getResultList();
proxies = new ArrayList<Proxy>(list);
tx.commit();
} finally {
tx.end();
}
return proxies;
}
}
java-class:
package com.company.tenderflow.parser;
public class Connector {
@Inject
private ProxyBean proxyBean;
//For GET queryes
public static Document getDoc(String url) {
Connector con = new Connector();
Proxy proxy = con.getProxy();
Document doc = null;
try {
if (proxy!=null)
doc = Jsoup.connect(url).proxy(proxy.getIp(), proxy.getPort()).timeout(30000).get();
else
doc = Jsoup.connect(url).timeout(30000).get();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
//For POST queryes
public static Document getDoc(String url, HashMap<String, String> data) {
Connector con = new Connector();
Proxy proxy = con.getProxy();
Document doc = null;
try {
if (proxy!=null)
doc = Jsoup.connect(url).proxy(proxy.getIp(), proxy.getPort()).timeout(60000).data(data).post();
else
doc = Jsoup.connect(url).timeout(60000).data(data).post();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
public Proxy getProxy(){
ArrayList<Proxy> proxies = proxyBean.getProxies(); // here the exception is thrown
System.out.println("PROXIES: " + proxies.size());
int i = 0 + (int) (Math.random() * proxies.size());
System.out.println("PROXY: " + proxies.get(i));
return proxies.size() > 0 ? proxies.get(i) : null;
}
}
Does it make sense that these 2 classes are located in different packages but in the same core module?