No bean named 'dataMapper' available - java

I have bean below bean in dto-mapping-v2-spring.xml which is under WEB-INF/config folder.
<alias alias="dataMapper" name="defaultDataMapper"/>
<bean id="defaultDataMapper"
class="de.hybris.platform.webservicescommons.mapping.impl.DefaultDataMapper">
<property name="fieldSetBuilder" ref="fieldSetBuilder"/>
</bean>
I trying to inject it in one of my service.I added this configuration in spring.xml under resources folder.
<alias name="defaultProductExportService" alias="ProductExportService"/>
<bean class="com.service.DefaultProductExportService" id="defaultProductExportService">
<property name="datamapper" ref="datamapper" />
</bean>
During server start it is throwing and error saying
Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataMapper' available
How I can inject bean?

Class inside extension/src/ with its bean definition inside resources/extension-spring.xml cannot access bean that's inside web/webroot/WEB-INF/, bean inside WEB-INF can only be accessed by class inside web/src/ or commonweb/src
extension
| - src/
| - resources
| | - extension-spring.xml
|
| - web
| -- src/
| -- webroot / WEB-INF / config

The answer of #Adiputera is correct but if someone still needs it:
Getting bean from any context using groovy script in hybris:
import de.hybris.platform.core.PK
import de.hybris.platform.spring.HybrisContextLoaderListener
import org.apache.commons.lang3.reflect.FieldUtils
import org.springframework.web.context.ContextLoader
import org.springframework.web.context.WebApplicationContext
STOREFRONTCONTEXT = "previewwebservices"
def f = ContextLoader.getDeclaredField("currentContextPerThread")
f.setAccessible(true)
Map<ClassLoader, WebApplicationContext> contexts = f.get(HybrisContextLoaderListener)
def appContext = contexts.find {STOREFRONTCONTEXT.equals(it.key.getContextName())}
//When the context is found, we are ready to get our beans
if (appContext ==null) println "Impossible to retrieve application context"
else {
defaultSyncService = appContext.value.getBean("synchronizationService")
}
ref:
https://www.stackextend.com/hybris/getting-bean-from-any-context-using-groovy-script-in-hybris/
or with JAVA:
public DataMapper getDataMapper() {
DataMapper dataMapper = null;
try {
String STOREFRONTCONTEXT = "commercewebservices";
Field f = ContextLoader.class.getDeclaredField("currentContextPerThread");
f.setAccessible(true);
Map<HybrisWebappLoader.HybrisWebappClassLoader, WebApplicationContext> contexts = (Map<HybrisWebappLoader.HybrisWebappClassLoader, WebApplicationContext>) f.get(HybrisContextLoaderListener.class);
Optional<HybrisWebappLoader.HybrisWebappClassLoader> appContextKey = contexts.keySet().stream().filter(key -> key.getContextName().equals(STOREFRONTCONTEXT)).findFirst();
if (appContextKey.isPresent()) {
dataMapper = contexts.get(appContextKey.get()).getBean("dataMapper", DataMapper.class);
}
} catch (IllegalAccessException | NoSuchFieldException e) {
LOG.error("Impossible to retrieve application context", e);
}
return dataMapper;
}

Related

How to add properties file to Spring XML context?

Here is the structure of sample Spring application
src
main
my.example
- MyBean.java
- AppMain.java
resources
- applicationContext.xml
- some.properties
applicationContext.xml
<beans ...>
<context:property-placeholder location="classpath:some.properties"/>
<bean id="a" class="my.example.MyBean"/>
</beans>
some.properties
myprop=something
AppMain.java
public class AppMain {
public static void main(String[] args) {
var context = new ClassPathXmlApplicationContext();
context.setConfigLocations("classpath:applicationContext.xml");
context.refresh();
var bean = context.getBean("a");
println(bean); // available
ConfigurableEnvironment environment = context.getEnvironment();
String javaHome = environment.getProperty("java.home");
String myprop = environment.getProperty("myprop");
println(environment.getPropertySources());
println("javaHome is " + javaHome); // ok
println("myprop is " + myprop); // is null
}
}
Output:
my.example.MyBean#cecf639
[PropertiesPropertySource {name='systemProperties'}, SystemEnvironmentPropertySource {name='systemEnvironment'}]
javahome is [/mypath/to/java/17.0.5-zulu]
myprop is [null]
As the output shows the property sources do not contains some.properties file, and hence myprop is null. At the same time the bean MyBean is available, which means applicationContext.xml was processed.
Why <context:property-placeholder ...> had no effect?
How to add some.properties file to the context, and get correct myprop value?

Spring java.lang.NoClassDefFoundError error

I am new to spring framework and following the tutorial on tutorialspoint.com. After including every thing, while running the program it gives me following error:
Error: Unable to initialize main class com.raza.spring.MainApp
Caused by: java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContext
Below is my project structure:
enter image description here
Here is the code:
Class Hello:
package com.raza.spring;
public class Hello {
private String message;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
}
Class MainApp:
package com.raza.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Hello obj = (Hello) context.getBean("helloWorld");
obj.getMessage();
}
}
Beans.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "helloWorld" class = "com.raza.spring.Hello">
<property name = "message" value = "Hello raza world !!!"/>
</bean>
</beans>
Not able to get what is wrong here. Thanks in advance.
I am trying tutorial on tutorialspoint.com and expecting an output on the console.
java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContext tells that the Class you are using in your code is not accessible from your project.
In previous chapter on https://www.tutorialspoint.com/spring/spring_environment_setup.htm you probably downloaded spring library in step 4. Try adding it to your classpath: https://wiki.eclipse.org/FAQ_How_do_I_add_an_extra_library_to_my_project%27s_classpath%3F.
I highly recommend you start using maven. It allows you to add external libraries a lot easier, without having to manually download them from a git repo or a website.
Also, check the Baeldung courses. Their examples always use the latest Spring version https://www.baeldung.com/spring-tutorial

How to get a service bean inside a custom tag library class in Grails 3

I want to get a service bean from the application context inside my custom tag library. The service name i will get it from the custom tag attribute.
This is the code i previously used.
class CustomTagLib {
static defaultEncodeAs = [taglib:'html']
//static encodeAsForTags = [tagName: [taglib:'html'], otherTagName: [taglib:'none']]
def selectList = { attrs ->
try{
String servName=attrs.service
String servMethod=attrs.method
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext())
def myservice=ctx."${servName}"
attrs.from = myservice.invokeMethod(servMethod,null);
out << g.select( attrs )
}catch(Exception e){
println("Exception in CustomTagLib in method selectList:"+e)
}
}
}
This code is worked me for Grails 2.3 version but not for version 3.
Please help me to find out a solution.
Try the following:
import grails.util.Holders
def myservice = Holders.getApplicationContext().getBean( servName )
Where servName would be your service name with lowercase first letter & camel case for the remainder

Read xml from an external jar not included in classpath

I created a javafx project using Netbeans, the project itself works just fine.
I'm now trying to implement a custom light-weight plugin system, the plugins are external JARs located inside the plugins/ directory of the main project. I'm using javax.security package to sandbox the plugins.
Here's the main project's structure:
MainProject
|
|---plugins/
| |---MyPlugin.jar
|
|---src/
| |---main.app.plugin
| |---Plugin.java
| |---PluginSecurityPolicy.java
| |---PluginClassLoader.java
| |---PluginContainer.java
....
And the plugin's one:
Plugin
|
|---src/
| |---my.plugin
| | |---MyPlugin.java
| |--settings.xml
|
|---dist/
|---MyPlugin.jar
|---META-INF/
| |---MANIFEST.MF
|---my.plugin
| |---MyPlugin.class
|---settings.xml
To load the plugins into the program i've made a PluginContainer class that gets all the jar files from the plugins directory, lists all file inside the jar and lookup for the plugin file and the settings file.
I can load and make an instance of the plugin class, but when it comes to the XML there's no way i can even list it among the jar contents.
Here's the code, maybe someone can see where i did it wrong.
PluginSecurityPolicy.java
import java.security.AllPermission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
import java.security.ProtectionDomain;
public class PluginSecurityPolicy extends Policy {
#Override
public PermissionCollection getPermissions(ProtectionDomain domain) {
if (isPlugin(domain)) {
return pluginPermissions();
} else {
return applicationPermissions();
}
}
private boolean isPlugin(ProtectionDomain domain) {
return domain.getClassLoader() instanceof PluginClassLoader;
}
private PermissionCollection pluginPermissions() {
Permissions permissions = new Permissions();
//
return permissions;
}
private PermissionCollection applicationPermissions() {
Permissions permissions = new Permissions();
permissions.add(new AllPermission());
return permissions;
}
}
PluginClassLoader.java
import java.net.URL;
import java.net.URLClassLoader;
public class PluginClassLoader extends URLClassLoader {
public PluginClassLoader(URL jarFileUrl) {
super(new URL[] {jarFileUrl});
}
}
PluginContainer.java, the #load method is the one
import main.app.plugin.PluginClassLoader;
import main.app.plugin.PluginSecurityPolicy;
import java.io.File;
import java.net.URL;
import java.security.Policy;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class PluginContainer {
private ArrayList<Plugin> plugins;
private ManifestParser parser;
public PluginContainer() {
Policy.setPolicy(new PluginSecurityPolicy());
System.setSecurityManager(new SecurityManager());
plugins = new ArrayList<>();
parser = new ManifestParser();
}
public void init() {
File[] dir = new File(System.getProperty("user.dir") + "/plugins").listFiles();
for (File pluginJarFile : dir) {
try {
Plugin plugin = load(pluginJarFile.getCanonicalPath());
plugins.add(plugin);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
public <T extends Plugin> T getPlugin(Class<T> plugin) {
for (Plugin p : plugins) {
if (p.getClass().equals(plugin)) {
return (T)p;
}
}
return null;
}
private Plugin load(String pluginJarFile) throws Exception {
PluginManifest manifest = null;
Plugin plugin = null;
// Load the jar file
ZipFile jarFile = new ZipFile(pluginJarFile);
// Get all jar entries
Enumeration allEntries = jarFile.entries();
String pluginClassName = null;
while (allEntries.hasMoreElements()) {
// Get single file
ZipEntry entry = (ZipEntry) allEntries.nextElement();
String file = entry.getName();
// Look for classfiles
if (file.endsWith(".class")) {
// Set class name
String classname = file.replace('/', '.').substring(0, file.length() - 6);
// Look for plugin class
if (classname.endsWith("Plugin")) {
// Set the class name and exit loop
pluginClassName = classname;
break;
}
}
}
// Load the class
ClassLoader pluginLoader = new PluginClassLoader(new URL("file:///" + pluginJarFile));
Class<?> pluginClass = pluginLoader.loadClass(pluginClassName);
// Edit as suggested by KDM, still null
URL settingsUrl = pluginClass.getResource("/settings.xml");
manifest = parser.load(settingsUrl);
// Check if manifest has been created
if (null == manifest) {
throw new RuntimeException("Manifest file not found in " + pluginJarFile);
}
// Create the plugin
plugin = (Plugin) pluginClass.newInstance();
plugin.load(manifest);
return plugin;
}
}
And the autogenerated MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.9.4
Created-By: 1.8.0_25-b18 (Oracle Corporation)
The Class-Path directive is missing, but if i force it to . or ./settings.xml or settings.xml (by manually editing the MANIFEST.MF file) it won't work either.
This is all I can think of, Thanks in advance for any help
[EDIT] I've created an images/monitor-16.png into the plugin jar root, added the #load2 method into the PluginContainer.
Since the method is called within a loop I left the Policy.setPolicy(new PluginSecurityPolicy()); and System.setSecurityManager(new SecurityManager()); inside the constructor.
Here's the new plugn jar structure:
TestPlugin.jar
|
|---META-INF/
| |---MANIFEST.MF
|
|---dev.jimbo
| |---TestPlugin.class
|
|---images
| |---monitor-16.png
|
|---settings.xml
The new method code:
private Plugin load2(String pluginJarFile) throws MalformedURLException, ClassNotFoundException {
PluginClassLoader urlCL = new PluginClassLoader(new File(pluginJarFile).toURL());
Class<?> loadClass = urlCL.loadClass("dev.jimbo.TestPlugin");
System.out.println(loadClass);
System.out.println("Loading the class using the class loader object. Resource = " + urlCL.getResource("images/monitor-16.png"));
System.out.println("Loading the class using the class loader object with absolute path. Resource = " + urlCL.getResource("/images/monitor-16.png"));
System.out.println("Loading the class using the class object. Resource = " + loadClass.getResource("images/monitor-16.png"));
System.out.println();
return null;
}
Here's the output
class dev.jimbo.TestPlugin
Loading the class using the class loader object. Resource = null
Loading the class using the class loader object with absolute path. Resource = null
Loading the class using the class object. Resource = null
The following program:
public static void main(String[] args) throws MalformedURLException, ClassNotFoundException {
Policy.setPolicy(new PluginSecurityPolicy());
System.setSecurityManager(new SecurityManager());
PluginClassLoader urlCL = new PluginClassLoader(new File(
"A Jar containing images/load.gif and SampleApp class").toURL());
Class<?> loadClass = urlCL.loadClass("net.sourceforge.marathon.examples.SampleApp");
System.out.println(loadClass);
System.out.println("Loading the class using the class loader object. Resource = " + urlCL.getResource("images/load.gif"));
System.out.println("Loading the class using the class loader object with absolute path. Resource = " + urlCL.getResource("/images/load.gif"));
System.out.println("Loading the class using the class object. Resource = " + loadClass.getResource("images/load.gif"));
}
Produces the following output:
class net.sourceforge.marathon.examples.SampleApp
Loading the class using the class loader object. Resource = jar:file:/Users/dakshinamurthykarra/Projects/install/marathon/sampleapp.jar!/images/load.gif
Loading the class using the class loader object with absolute path. Resource = null
Loading the class using the class object. Resource = null
So I do not think any problem with your class loader. Putting this as an answer so that the code can be formatted properly.
Nailed it! Seems that my previous Netbeans (8.0) was deleting the plugin directory from the added Jar/Folder Libraries references on Clean and Build action. I've downloaded and installed Netbeans 8.0.2 and the problem was solved. Couldn't find any related bug for that version on their tracker though..
Anyways Thanks for the help :)

Error: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'nimoConfigurationBean' is defined

I am using Spring in my Jar file to get the properties from a properties file. I am getting output when i try from my RAD(eclipse). but when i deploy my jar file in server, i keep getting this error.
ERROR:
Exception
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'nimoConfigurationBean' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:509)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1041)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:273)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1044)
The error occurs when i get bean:
**NimoConfigurationBean obj = (NimoConfigurationBean) context.getBean("nimoConfigurationBean");**
XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/util http://xml.westfieldgrp.com/public/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/beans http://xml.westfieldgrp.com/public/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jee http://xml.westfieldgrp.com/public/schema/jee/spring-jee-3.0.xsd" >
<bean id="applicationProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:/config/devint/nimo.properties"/>
</bean>
<bean id="nimoConfigurationBean" scope="singleton"
class="com.westfieldgrp.filenet.env.NimoConfigurationBean">
<property name="serviceUser" value="${env.user}" />
<property name="servicePass" value="${env.pass}" />
</bean>
</beans>
Call in Java:
public class AddEnvProperty {
public String envType(String propertyValue) {
String returnValue = "";
AddEnvProperty envProps = new AddEnvProperty();
NimoConfigurationBean nimoConfigurationBean = envProps.getConfig();
PluginLogger logger = new PluginLogger(new ResponceFilterPlugin());
logger.logDebug(this, "envType", "Getting Property Value" + propertyValue);
try {
if (propertyValue == "USER") {
returnValue = nimoConfigurationBean.getServiceUser();
} else if (propertyValue == "PASS") {
returnValue = nimoConfigurationBean.getServicePass();
}
} catch (NullPointerException ex) {
// TODO Auto-generated catch block
logger.logError(this, "envType", "NullPointerException:", ex);
}catch (Exception ex) {
// TODO Auto-generated catch block
logger.logError(this, "envType", "NullPointerException:", ex);
}
return returnValue;
}
private NimoConfigurationBean getConfig() {
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath*:/com/xml/*applicationContext.xml");
NimoConfigurationBean obj = (NimoConfigurationBean) context.getBean("nimoConfigurationBean");
return obj;
}
}
Getter, setter methods in NimoConfigurationBean.java
NoSuchBeanDefinitionException is thrown by Spring container, if the bean configurable sources is not available at load time. In your case the configurable source is XML, i.e. your application context xml is not available to spring. make sure that your XML is packaged and available to class path.

Categories