In database: there is a field whos type is TINYINT(1) and default value is 0. And in Model it is defined as TINYINT(1) DEFAULT 0. However it gives error such as below:
Error
[jar:file:/C:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/NetaCommerceFrameworkAdmin/WEB-INF/lib/NetaCommerceFramework-0.0.1-SNAPSHOT.jar!/com/netasoft/commerce/framework/lang/dao/LangDaoImpl.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type
[org.hibernate.SessionFactory]: :Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/admin-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Wrong column type in kaft.nc_alert_log for column alerted. Found: bit, expected: TINYINT(1) DEFAULT 0; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/admin-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Wrong column type in kaft.nc_alert_log for column alerted. Found: bit, expected: TINYINT(1) DEFAULT 0
Model definition
#Column(name="alerted", columnDefinition = "TINYINT(1) DEFAULT 0")
private int alerted;
public int getAlerted() {
return alerted;
}
public void setAlerted(int alerted) {
this.alerted = alerted;
}
Db.properties
hibernate.hbm2ddl.auto=validate
#hibernate.hbm2ddl.auto=create-drop
hibernate.hbm2ddl.import_files=/import_standard.sql
hibernate.show_sql=false
hibernate.format_sql=true
hibernate.generate_statistics=false
hibernate.use_sql_comments=true
hibernate.query.factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory
hibernate.cache.use_second_level_cache=true
#-------------------------------------------------------------------------------
# MySQL Settings
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/xxx?autoReconnect=true
jdbc.username=xxx
jdbc.password=xxx
# Property that determines which Hibernate dialect / MySQL5Dialect || MySQLDialect
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
Dialect Versions:
2013-01-17 08:45:36,920 INFO [org.hibernate.cfg.SettingsFactory] - Database ->
name : MySQL
version : 5.0.96-community-nt
major : 5
minor : 0
2013-01-17 08:45:36,921 INFO [org.hibernate.cfg.SettingsFactory] - Driver ->
name : MySQL-AB JDBC Driver
version : mysql-connector-java-5.1.12 ( Revision: ${bzr.revision-id} )
major : 5
minor : 1
it is running on server and another computer, too. However in my computer and new computer which is installed just to try it gives same error. I am searching for days on google, couldnt figure out what caueses the issue. Tried boolean columnDefinition in model and change MySqlDialect definition however nothing change. Even error message is same.
Use BIT as columnDefinition
This worked for me:
#Column(name = "my_field",columnDefinition = "BIT")
private int myField;
You can use tinyInt1isBit=false mysql driver parameter. i.e. jdbc:mysql://localhost?tinyInt1isBit=false
http://dev.mysql.com/doc/refman/5.5/en/connector-j-reference-configuration-properties.html
This prevent driver from reporting back tinyint(1) columns as java.sql.Type.BIT
However you may start getting issues with boolean fields if they are represented in the DB as tinyint(1) as well.
Add the #Type annotation to the alerted field as follows:
#org.hibernate.annotations.Type(type="true_false")
#Column(name="alerted", columnDefinition = "TINYINT(1) DEFAULT 0")
private int alerted;
Related
I get the following exception:
org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'modifyPopulatorList$child#0' defined in class path resource [config/cmsfacades-cmsitems-spring.xml]: Initialization of bean failed;
Error creating bean with name 'ordermanagementOrderConverter' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementOrderPopulator' while setting bean property 'populators' with key [0];
Error creating bean with name 'ordermanagementOrderPopulator' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementOrderEntryConverter' while setting bean property 'orderEntryConverter';
Error creating bean with name 'ordermanagementOrderEntryConverter' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementOrderEntryPopulator' while setting bean property 'populators' with key [0];
Error creating bean with name 'warehousingOrderEntryPopulator' defined in class path resource [warehousingfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementProductConverter' while setting bean property 'productConverter';
Error creating bean with name 'ordermanagementProductConverter' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementProductPopulator' while setting bean property 'populators' with key [0];
Error creating bean with name 'ordermanagementProductPopulator' defined in class path resource [ordermanagementfacades-spring.xml]: Error setting property values;
Invalid property 'designerConverter' of bean class [de.hybris.platform.ordermanagementfacades.product.converters.populator.OrdermanagementProductBasicPopulator]: Bean property 'designerConverter' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
This is my bean registration :
<alias name="defaultCustomProductBasicPopulator" alias="productBasicPopulator"/>
<bean id="defaultCustomProductBasicPopulator" parent="defaultProductBasicPopulator"
class="de.hybris.NagAcc.facades.product.converters.populator.CustomProductBasicPopulator">
<property name="designerConverter" ref="designerConverter" />
</bean>
This is the class :
public class CustomProductBasicPopulator<SOURCE extends ProductModel, TARGET extends ProductData> extends ProductBasicPopulator<SOURCE,TARGET> {
private Converter<DesignerModel,DesignerData> designerConverter;
public Converter<DesignerModel, DesignerData> getDesignerConverter() {
return designerConverter;
}
public void setDesignerConverter(Converter<DesignerModel, DesignerData> designerConverter) {
this.designerConverter = designerConverter;
}
#Override
public void populate(SOURCE productModel, TARGET productData) throws ConversionException {
super.populate(productModel, productData);
if (productModel.getDesigner() != null)
{
DesignerData designerData = getDesignerConverter().convert(productModel.getDesigner());
productData.setDesigner(designerData);
}
}
This is the parent bean definition :
<alias name="defaultProductBasicPopulator" alias="productBasicPopulator"/>
<bean id="defaultProductBasicPopulator" parent="baseProductPopulator"
class="de.hybris.platform.commercefacades.product.converters.populator.ProductBasicPopulator">
<property name="productConfigurableChecker" ref="productConfigurableChecker"/>
</bean>
The complete stack trace:
org.springframework.beans.FatalBeanException: Context hybris Global Context Factory couldn't be created correctly due to, Error creating bean with name 'modifyPopulatorList$child#0' defined in class path resource [config/cmsfacades-cmsitems-spring.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ordermanagementOrderConverter' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementOrderPopulator' while setting bean property 'populators' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ordermanagementOrderPopulator' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementOrderEntryConverter' while setting bean property 'orderEntryConverter'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ordermanagementOrderEntryConverter' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementOrderEntryPopulator' while setting bean property 'populators' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'warehousingOrderEntryPopulator' defined in class path resource [warehousingfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementProductConverter' while setting bean property 'productConverter'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ordermanagementProductConverter' defined in class path resource [ordermanagementfacades-spring.xml]: Cannot resolve reference to bean 'ordermanagementProductPopulator' while setting bean property 'populators' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ordermanagementProductPopulator' defined in class path resource [ordermanagementfacades-spring.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'designerConverter' of bean class [de.hybris.platform.ordermanagementfacades.product.converters.populator.OrdermanagementProductBasicPopulator]: Bean property 'designerConverter' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at de.hybris.platform.core.HybrisContextFactory.build(HybrisContextFactory.java:307)
at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.buildSelf(HybrisContextFactory.java:179)
at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.build(HybrisContextFactory.java:165)
at de.hybris.platform.core.HybrisContextHolder.getGlobalInstanceCached(HybrisContextHolder.java:122)
at de.hybris.platform.core.HybrisContextHolder.getGlobalInstance(HybrisContextHolder.java:101)
at de.hybris.platform.core.HybrisContextHolder.getAppCtxFactory(HybrisContextHolder.java:152)
at de.hybris.platform.core.HybrisContextHolder.getApplicationInstance(HybrisContextHolder.java:78)
at de.hybris.platform.core.AbstractTenant.createCoreApplicationContext(AbstractTenant.java:758)
at de.hybris.platform.core.AbstractTenant.doStartupSafe(AbstractTenant.java:799)
... 22 more
According to me all getters and setters are fine, I can not resolve this error. Please help.
I don't have access to hybris sources to have a look (thank god!), but I think it's worth to have a look at the Javadoc of OrdermanagementProductBasicPopulator:
public void populate(ProductModel productModel, ProductData productData)
Description copied from interface: Populator
Populate the target instance with values from the source instance.
Overrides:
populate in class ProductBasicPopulator
So I guess, the class OrdermanagementProductBasicPopulator extends ProductBasicPopulator but the bean definition of OrdermanagementProductBasicPopulator has your productBasicPopulator as a parent, which means that spring tries to inject the property of your bean definition, which is not a property in the inheritance chain of OrdermanagementProductBasicPopulator.
As mentioned, this is just a guess because I don't see the sources...
If my guess is correct, it depends on your requirements how to get rid of this problem. You can either give your bean a new alias and modify the populator list(s) where necessary or you override the bean alias of OrdermanagementProductBasicPopulator accordingly.
If thats's not the problem, please post the bean definition of OrdermanagementProductBasicPopulator.
Here i'm trying to receive Upload file in Graphql. My Code as follows
Graphql schema example.graphqls
scalar Upload
type Mutation {
uploadFile(input: CreateFileUploadInput): Boolean
}
input CreateFileUploadInput {
files: Upload
id: String
}
Graphql Scalar upload defined in GraphqlConfig.java
#Configuration
public class GraphqlConfig {
#Bean
public SchemaParserOptions schemaParserOptions(
GraphQlObjectMapperConfigurer customObjectMapperConfigurer) {
return SchemaParserOptions.newOptions().objectMapperConfigurer(customObjectMapperConfigurer)
.build();
}
#Bean
GraphQLScalarType upload() {
return graphql.servlet.ApolloScalars.Upload;
}
}
Graphql Objectmapper configurer GraphQlObjectMapperConfigurer.java
#Component
public class GraphQlObjectMapperConfigurer implements ObjectMapperConfigurer {
#Override
public void configure(ObjectMapper mapper, ObjectMapperConfigurerContext context) {
mapper.registerModule(new JavaTimeModule())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.setTimeZone(TimeZone.getDefault());
}
}
my Model class CreateFileUploadInput.java
#Data
#NoArgsConstructor
#AllArgsConstructor
public class CreateFileUploadInput {
private Part files;
private String id;
}
I'm using graphql spring boot version in build.gradle is 5.8.1 and gradle gradle-5.6.2-bin
Im getting below Exception while i run my Spring Boot application!
2020-01-17 15:20:24.618 WARN 37316 --- [ main] c.c.graphql.tools.SchemaClassScanner : Cannot find definition for field 'files: Upload' on input type 'CreateFileUploadInput' -> javax.servlet.http.Part. Try adding it manually to the dictionary
2020-01-17 15:20:24.665 WARN 37316 --- [ main] c.c.graphql.tools.SchemaClassScanner : Schema type was defined but can never be accessed, and can be safely deleted: Upload
2020-01-17 15:20:24.665 WARN 37316 --- [ main] c.c.graphql.tools.SchemaClassScanner : Schema type was defined but can never be accessed, and can be safely deleted: PageInfo
2020-01-17 15:20:24.752 ERROR 37316 --- [ main] o.s.b.web.embedded.tomcat.TomcatStarter : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'graphQLServletRegistrationBean' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLServletRegistrationBean' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLHttpServlet' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLHttpServlet' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLServletConfiguration' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLServletConfiguration' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'invocationInputFactory' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'invocationInputFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLSchemaProvider' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLSchemaProvider' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'graphQLSchema' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLJavaToolsAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [graphql.schema.GraphQLSchema]: Factory method 'graphQLSchema' threw exception; nested exception is com.coxautodev.graphql.tools.SchemaError: Expected type 'Upload' to be a GraphQLInputType, but it wasn't! Was a type only permitted for object types incorrectly used as an input type, or vice-versa?
2020-01-17 15:20:24.789 INFO 37316 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-01-17 15:20:24.794 WARN 37316 --- [ main] o.a.c.loader.WebappClassLoaderBase : The web application [ROOT] appears to have started a thread named [HikariPool-1 housekeeper] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
sun.misc.Unsafe.park(Native Method)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [graphql.schema.GraphQLSchema]: Factory method 'graphQLSchema' threw exception; nested exception is com.coxautodev.graphql.tools.SchemaError: Expected type 'Upload' to be a GraphQLInputType, but it wasn't! Was a type only permitted for object types incorrectly used as an input type, or vice-versa?
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
... 128 common frames omitted
Caused by: com.coxautodev.graphql.tools.SchemaError: Expected type 'Upload' to be a GraphQLInputType, but it wasn't! Was a type only permitted for object types incorrectly used as an input type, or vice-versa?
at com.coxautodev.graphql.tools.SchemaParser.determineType(SchemaParser.kt:350) ~[graphql-java-tools-5.6.0.jar:na]
I have been spending lot of times to investigate this issue, still i could't solve it. Pls help!
I encountered this error when I tried to use a type rather than input as an input, which isn't allowed. This is slightly different from the original question, but you'll see the same error:
So this was NOT working:
scalar Upload
type Mutation {
uploadFile(input: CreateFileUploadInput): Boolean
}
type CreateFileUploadInput {
files: Upload
id: String
}
This fixed it:
input CreateFileUploadInput {
files: Upload
id: String
}
(Just changed it from type to input)
I was having the same problem over here and was able to solve it (be it not in a very nice way) after reading something mentioned on https://github.com/graphql-java-kickstart/graphql-java-tools/issues/77.
It states that by using the type explicitly in the root of a query/mutation, it will also be available on a nested level. In your case this would mean adding an additional method e.g. typLoaderDummy, as shown in the sample below (which will not actually be used) to your definition. Keep in mind that you will need to provide an implementation for this "dummy" method on your Java implementation.
scalar Upload
type Mutation {
uploadFile(input: CreateFileUploadInput): Boolean
typeLoaderDummy(upload: Upload): Boolean
}
For me this workaround solved the problem.
My environment variable is a string with time 23:30 In my String Boot application I'd like to parse it automatically and set it the result to variable.
I tried like this
#Value("#{ java.time.LocalTime.parse('${NIGHT_START_TIME}')}")
private LocalTime NIGHT_START_TIME;
IntelliJ shows the error
Cannot resolve variable 'java'
Here is log
Unsatisfied dependency expressed through field 'NIGHT_START_TIME';
nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'LocalTime' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
If I read variable like this I see that value is correct
#Value("${NIGHT_START_TIME}")
private String NIGHT_START_TIME;
Any ideas how to make it work?
Try this
#Value("#{ T(java.time.LocalTime).parse('${NIGHT_START_TIME}')}")
private LocalTime NIGHT_START_TIME;
The way you reference a class is using T.
Check the documentation.
Have checked at Spring Boot 2.2.6.RELEASE:
application.yml
NIGHT_START_TIME: '23:30'
Service
#Value("${NIGHT_START_TIME}")
private LocalTime NIGHT_START_TIME;
Work perfect without any "knee bends":)
I'm new to Grails so I posted a question a few days ago on how to do a query to a different Datasource:
Grails - Getting data from a different datasource and saving it in my Grails database
The answer above worked, but then I got a strange error when I tried to view or modify anything in my default datasource. In this case I tried to go to index view of my Client controller which uses some basic scaffolding:
[http-bio-8080-exec-10] ERROR spring.ReloadAwareAutowireCapableBeanFactory - Bean couldn't be autowired using grails optimization: Error creating bean with name 'properties': Bean definition is abstract
[http-bio-8080-exec-10] ERROR spring.ReloadAwareAutowireCapableBeanFactory - Retrying using spring autowire
[http-bio-8080-exec-10] ERROR errors.GrailsExceptionResolver - BeanIsAbstractException occurred when processing request: [GET] /EmmaRestServer/client/index
Error creating bean with name 'properties': Bean definition is abstract. Stacktrace follows:
Message: Error creating bean with name 'properties': Bean definition is abstract
If I remove the second datasource, this problem disappears. What could be causing this issue?
I had some extra configurations in the resources.groovy. I removed them and now it looks like this, and it works properly:
beans = {
dataSource_drupal(DataSource) { bean ->
bean.destroyMethod = 'close'
driverClassName = "com.mysql.jdbc.Driver"
username = "user"
password = "password"
url = "jdbc:databaseURL
}
}
I'm having trouble injecting JNDI values from my Tomcat into spring java config using the #Value annotation whereas I have no trouble retreiving the values via the Environment class. We are using Java 1.7.0_17, Spring 4.0.3, and Tomcat 7.0.52 .
I have in my context.xml the following variables defined:
<Environment name="USER_NAME" value="initech" type="java.lang.String" />
<Environment name="USER_PASSWORD" value="1n3+3ch!" type="java.lang.String" />
In my Java configuration file I have the following code working:
#Bean
public Foo foo( Environment env ){
return new Foo( env.getProperty("USER_NAME"), env.getProperty("USER_PASSWORD") );
}
When I look into the server log I see:
12:50:45.214 [RMI TCP Connection(3)-127.0.0.1] DEBUG o.s.c.e.PropertySourcesPropertyResolver -> Searching for key 'USER_NAME' in [servletConfigInitParams]
12:50:45.214 [RMI TCP Connection(3)-127.0.0.1] DEBUG o.s.c.e.PropertySourcesPropertyResolver -> Searching for key 'USER_NAME' in [servletContextInitParams]
12:50:45.214 [RMI TCP Connection(3)-127.0.0.1] DEBUG o.s.c.e.PropertySourcesPropertyResolver -> Searching for key 'USER_NAME' in [jndiProperties]
12:50:45.214 [RMI TCP Connection(3)-127.0.0.1] DEBUG o.springframework.jndi.JndiTemplate -> Looking up JNDI object with name [java:comp/env/USER_NAME]
12:50:45.214 [RMI TCP Connection(3)-127.0.0.1] DEBUG o.s.jndi.JndiLocatorDelegate -> Located object with JNDI name [java:comp/env/USER_NAME]
12:50:45.214 [RMI TCP Connection(3)-127.0.0.1] DEBUG o.s.jndi.JndiPropertySource -> JNDI lookup for name [USER_NAME] returned: [initech]
12:50:45.214 [RMI TCP Connection(3)-127.0.0.1] DEBUG o.s.c.e.PropertySourcesPropertyResolver -> Found key 'USER_NAME' in [jndiProperties] with type [String] and value 'initech'
However, I would like to use #Value annotation to make the code cleaner if at all possible; something along the lines of
#Bean
public Foo foo(
#Value( "#{USER_NAME}" ) String userName,
#Value( "#{USER_PASSWORD}" ) String userPassword
){
return new Foo( userName, userPassword );
}
but this code results in the error:
nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'USER_NAME' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'USER_NAME' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'oauthTokenRequestClient' defined in class path resource [com/initech/set/gw/api/config/GatewayRepositoryConfig.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.net.URI]: : Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'USER_NAME' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'USER_NAME' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:747)
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:462)
I have tried "#{systemEnvironment.USER_NAME}, "#{systemProperties.USER_NAME}, "#{jndiProperties.USER_NAME}, and "#{java:comp/env/USER_NAME} as well: yet, none of them work.
PS- I've tried to simplify the question so if one of these should have worked let me know because I may have made an error in my posting.
I solved it using the selected answer from the question Java Spring: How to use #Value annotation to inject an Environment property?.
So my code looks like:
#Bean
public Foo foo(
#Value( "#{environment.USER_NAME}" ) String userName,
#Value( "#{environment.USER_PASSWORD}" ) String userPassword
){
return new Foo( userName, userPassword );
}
I'm assuming from the content of the most upvoted answer (ie "assuming that you have a PropertySourcesPlaceHolderConfigurer registered") to that quesiton that this means we are lacking a configured PropertySourcesPlaceHolderConfigurer.
If you are using Spring 4 you should change
#Value( "#{USER_PASSWORD}" ) String userPassword
To
#Value( "${USER_PASSWORD}" ) String userPassword
Try that and see what happens.
For Spring 3.1+ (tested on 4.2.5.RELEASE), you can use #Value like this:
#Value("${property.name}")
private String jndiProperty;
But you also need to define a PropertySourcesPlaceholderConfigurer bean in a static method and configure a JndiPropertySource (I have this in an #Configuration class):
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(ConfigurableEnvironment env) {
PropertySourcesPlaceholderConfigurer placeholderConfigurer = new PropertySourcesPlaceholderConfigurer();
JndiPropertySource jndiPropertySource = new JndiPropertySource("java:comp");
env.getPropertySources().addFirst(jndiPropertySource);
return placeholderConfigurer;
}
Note the use of addFirst() which ensures property values from JNDI take precedence in case of a clash with other property sources, which may or may not be desired, in which case one can use other methods like addLast() etc.
This is the correct syntex
#Value("${PASSWORD}")
Have a look at this example:
http://www.programsji.com/spring/readpropertyfile