How can I run a method Asynchronously with spring? - java

The following code is suppose to work Asynchronously but instead it waits for the Async part to finish and then goes. How can I make the blah() method run Asynchronously?
spring.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:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- Activates #Scheduled and #Async annotations for scheduling -->
<task:annotation-driven />
<bean id="test"
class="com.spring.test.Test">
</beans>
Test.java
#Path("/test")
public class Test
{
#GET
#Path("/test")
#Produces("text/plain")
public String tester()
{
return "Running...";
}
#GET
#Path("/triggerNew")
#Produces("text/plain")
public String triggerNew()
{
System.out.println("BEFORE " + new Date() + " BEFORE");
new Process().blah();
System.out.println("AFTER " + new Date() + " AFTER");
return "TRIGGERED";
}
}
Process.java
#Component
public class Process
{
#Async
public void blah()
{
try
{
Thread.currentThread().sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("NEW THREAD " + new Date() + " NEW THREAD");
}
}

#Async only works when you annotate Spring-managed beans, not arbitrary classes. You need to define Process as a Spring bean, and then inject it into your controller class, e.g.
<bean id="test" class="com.spring.test.Test">
<property name="process">
<bean class="com.spring.test.Process"/>
</property>
</bean>
public class Test {
private Process process;
public void setProcess(Process process) {
this.process = process;
}
...
public String triggerNew() {
process.blah();
}
}

Alternatively you can execute your task manually with TaskExecutor.
Just define executor in the context:
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"/>
Than you can execute yor task:
taskExecutor.execute(new Process ());
But in this case your Process class must implement Runnable interface

Related

Property from PropertySource is not used

I've got a question for programmatically added properties to a spring context.
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ConfigurableEnvironment ctxEnvironment = ctx.getEnvironment();
ctxEnvironment.getPropertySources().addFirst(new ResourcePropertySource("rootProperties", new FileSystemResource("/tmp/root.properties")));
ctx.load(new ClassPathResource("/context/application-context.xml"));
ctx.refresh();
root.properties:
test=hello
Snippet from application context:
...
<property name="test" value="${test} world"/>
...
When I load the bean from the context, ${test} is not substituted with "hello".
Spring version: 5.1.5.RELEASE
What am I missing here?
PS: Btw, this works:
System.out.println("Text: " + ctxEnvironment.resolvePlaceholders("${test}"));
Output:
Text: hello
EDIT: Sorry, I forgot to add: I don't want to use the context:property-placeholder bean, because I know the location of the properties file only at runtime.
I reproduced your case and it's working for me. You need to add a property place holder in your applicationContext.xml file :
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="file:/tmp/root.properties" />
<bean id="myA" class="com.zpavel.MyA">
<property name="test" value="${test}" />
</bean>
</beans>
For example a simple bean :
public class MyA {
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
You can load it with :
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/context/application-context.xml");
MyA myA = context.getBean(MyA.class);
System.out.println(myA.getTest());
It will print "hello" as expected.
Your code is working fine.
I have tested with this.
applicationContext.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder
location="application.properties" />
<bean id="demo"
class="com.example.Demo">
<property name="value1" value="${test} world" />
</bean>
</beans>
application.properties :
test = Hello
Demo.java :
public class Demo {
String value1;
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
#Override
public String toString() {
return value1;
}
}
Test.java :
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
Demo demo = (Demo) classPathXmlApplicationContext.getBean("demo");
System.out.println(demo);
classPathXmlApplicationContext.close();
}
}
When you run, the output :
Hello world
The problem is with the bean. Please check it.
After some more diving into the spring API I found a pure programmatic solution to my problem without the need of a context:property element. For anyone interested, here is the full source:
Test.java
public class Test {
public static void main(String[] args) throws Exception {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
MutablePropertySources propertySources = new MutablePropertySources();
propertySources.addFirst(new ResourcePropertySource("rootProperties", new ClassPathResource("/root.properties")));
configurer.setPropertySources(propertySources);
ctx.addBeanFactoryPostProcessor(configurer);
ctx.load(new ClassPathResource("/ctx.xml"));
ctx.refresh();
TestBean bean = ctx.getBean(TestBean.class);
System.out.println(bean.getString());
}
}
TestBean.java
public class TestBean {
String string = "";
public String getString() { return string; }
public void setString(String string) { this.string = string; }
}
ctx.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 classpath:/org/springframework/beans/factory/xml/spring-beans.xsd">
<beans>
<bean class="TestBean">
<property name="string" value="${test} world"/>
</bean>
</beans>
</beans>
root.properties
test=hello

Spring Cloud Gateway injection in Unit Tests is not Working

I have a Global Filter with an injected attribute.
public class AuthenticationGlobalFilter implements GlobalFilter, Ordered {
#Autowired
private Permission permission;
#Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
long serviceId = 0;
try {
ServerHttpRequest request = exchange.getRequest();
HttpHeaders headers = request.getHeaders();
String fromKey = headers.getFirst("x-api-key");
String fromIp = headers.getFirst("x-forwarded-for");
String fromSubject = headers.getFirst("******");
URI rqUrl = request.getURI();
String path = rqUrl.getPath();
serviceId = Long.parseLong(path.split("/")[6]);
permission.check(permission.identity(fromKey, fromSubject, fromIp), serviceId);
return chain.filter(exchange);
} catch (PermissionException e) {
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
} catch (IllegalArgumentException e) {
exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
} catch (Exception e) {
exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
}
return Mono.empty();
}
}
Injection works perfectly when I run the application
#EnableDiscoveryClient
#SpringBootApplication
#EnableConfigurationProperties(ApiGatewayProperties.class)
#Import({ PermitAllSecurityConfiguration.class, CustomAttributesConfiguration.class })
#ImportResource(value = { "classpath:datasource.xml", "classpath:api-gateway-unico-beans.xml" })
public class ApiGatewayUnicoApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayUnicoApplication.class, args);
}
}
With this configuration file:
<?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:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<cache:annotation-driven
cache-manager="cacheManager" />
<context:annotation-config />
<context:component-scan
base-package="*****.apigatewayunico" />
<bean
class="*****.apigatewayunico.filters.AuthenticationGlobalFilter" />
<bean class="*****.apigatewayunico.Persistence"
p:sql="SELECT rep.url FROM RestService rs, RestEndpoint rep WHERE rep.id = rs.endpoint_id AND rs.id = ? AND rs.available = true" />
<bean id="permission"
class=*****.permission.Permission" />
The problem is that when I make a unit test, the property is injected in the unit test by not in the filter being tested, giving me errors about not being able to locate a bean that can satisfy this dependency.
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = RANDOM_PORT)
#DirtiesContext
public class AuthenticationGlobalFilterIntegrationTests extends BaseWebClientTests {
#Autowired
private Permission permission;
#Before
public void setup() {
super.setup();
reset(permission);
permission.check(null, 123456L);
}
#Test
public void runSucessTest() {
expectLastCall();
replay(permission);
testClient.get().uri("/status/200").exchange().expectStatus().isEqualTo(HttpStatus.OK);
}
#Test
public void runPermissionExceptionTest() throws Exception {
expectLastCall().andThrow(new PermissionException(""));
replay(permission);
testClient.get().uri("/status/200").exchange().expectStatus().isEqualTo(HttpStatus.FORBIDDEN);
}
#EnableAutoConfiguration
#SpringBootConfiguration
#Import(DefaultTestConfig.class)
#ImportResource(value = "classpath:authentication-filter-test-beans.xml")
public static class TestConfig {
}
}
authentication-filter-test-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"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:api-gateway-unico-test-beans.xml" />
<bean id="authenticationFilter"
class="*****.apigatewayunico.filters.AuthenticationGlobalFilter">
</bean>
</beans>
api-gateway-unico-test-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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
default-lazy-init="false">
<bean id="mockSupport" class="org.easymock.EasyMockSupport" />
<bean id="pp" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="*****.permission.PermissionPersistence" />
<bean id="permission" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="*****.permission.Permission" />
<bean id="jdbc" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="org.springframework.jdbc.core.JdbcTemplate" />
<bean id="descoveryClienteMock" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="org.springframework.cloud.client.discovery.DiscoveryClient" />
<bean id="serviceInstanceMock" factory-bean="mockSupport"
factory-method="createNiceMock"
c:_0="org.springframework.cloud.client.ServiceInstance" />
</beans>
Now when I try to add the unit test's configuration xml to the #ConextConfiguration annotation in the unit test, I get a test related to Reactor dependencies!
org.springframework.context.ApplicationContextException: Unable to
start reactive web server
Solved by annotating the dependency with #Lazy

Couldn't pass the #bean value to another class through Autowiring

I am new to spring. So I couldn't figure out what issue is there in the below code. I have two classes. I am defining a #Bean Channel and am autowiring that bean in the next class. I am using annotation for autowiring. When I try " System.out.println(externalChannel.toString());" am getting null values and the exception null pointer exception is thrown.
#Configuration
public class MessagingConfig
{
#Value("${service.name}")
private String queueName; // NOSONAR
#Value("${${user}")
private String schema;
#Value("${Owner}")
private String owner;
#Bean
public Channel externalChannel()
{
EventsProvider eventsProvider = new EventsProvider();
eventsProvider.setOwner(owner);
System.out.println("-------Cost And Events Channel-------"+eventsProvider.getEventsChannel());
return eventsProvider.getEventsChannel();
}
}
And Another class is
#Component
#LoggedService
#Monitored(useActualType = true)
public class MessagePublish {
#Autowired
private MessagingService messageService;
#Autowired
private Channel externalChannel;
public void publishTPSMessage(SourceTransaction sourceTransaction)
{
TPSEvent event = new TPSEvent(ContextHolder.getContextId(), new Date(), GuidUtils.generateGuid(),sourceTransaction);
Message<TPSEvent> message = new Message<TPSEvent>(event);
message.getHeader().setMessageType(TPSEvent.class.getName());
message.getHeader().setPayloadEncodingType(SystemCodecs.XML.name());
System.out.println(message.toString());
System.out.println(externalChannel.toString());
messageService.publish(externalChannel, message);
}
}
More Info
public Channel getEventsChannel() {
return Channel.builder()
.setName("necessarySources")
.setConnectionName("defaultConnection")
.setType(ChannelType.Topic)
.setConnectionData(AqSqlConnectionData.buildString(this.owner, "Safi"))
.setSubscriberNames(new String[]{"Safi_Autowire"})
.build();
}
Main Class
public class TPSHandler {
public static void main(String[] args) {
BatchExport batchExportBean=getBatchExportASJAXBElement();
System.out.println(" batchExportBean Trans Description : " + batchExportBean.getDueDate());
for(Pay pay :batchExportBean.getPay()) {
SourceTransaction sourceTransaction=mapPayBatchToSourceTransaction(pay,batchExportBean);
String sourceTraString = getSourceTransactionASXML(sourceTransaction);
System.out.println(" sourceTraString : \n" + sourceTraString);
MessagePublish messagePublish= new MessagePublish();
//SourceTransaction sourceTransaction= new SourceTransaction();
messagePublish.publishTPSMessage(sourceTransaction);
}
}
}
My Servlet.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:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
<import resource="classpath:config-properties.xml" />
<import resource="classpath:datasource.xml" />
<import resource="classpath:transaction-manager.xml" />
<import resource="classpath:jmx.xml" />
<context:component-scan base-package="com.imosAdapter" />
<bean class="com.oasis.services.messaging.config.MessagingServicesConfig" />
<bean class="com.oasis.services.messaging.config.DefaultMessagingConnectorsConfig" />
<bean class="com.oasis.services.messaging.config.LoaderConfig" />
<context:annotation-config />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/config/oasis-component.properties</value>
</property>
</bean>
</beans>
The exception thrown:
Exception in thread "main" java.lang.NullPointerException
at com.imosAdapter.tps.events.MessagePublish.publishTPSMessage(MessagePublish.java:46)
at com.imosAdapter.tps.TPSHandler.main(TPSHandler.java:64)
What is the issue over here? Can anybody help me with this? what exactly I am missing here?
You need to initialize a Spring context at the start of your application when you do not create a servlet / run as a Server.
See Using Spring in a standalone application

Spring service class extends AbstractService and implements interface [duplicate]

I was using spring to create objects through beans. Now I tried to use aop to create the same object and I get $Proxy cannot be cast to SaleRoom exception.
the previous xml was:
<?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:aop="http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
xmlns:context="http://www.springframework.org/schema/context/spring-context-2.5.xsd"
xmlns:flow="http://www.springframework.org/schema/webflow-config/spring-webflow-config- 1.0.xsd"
xmlns:jm s="http://www.springframework.org/schema/jms/spring-jms-2.5.xsd"
xmlns:jee="http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"
xmlns:lang="http://www.springframework.org/schema/lang/spring-lang-2.5.xsd"
xmlns:osgi="http://www.springframework.org/schema/osgi/spring-osgi.xsd"
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
xmlns:util="http://www.springframework.org/schema/util/spring-util-2.5.xsd"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/aop/spring-aop-2.5.xsd/spring-spring-aop-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/context/spring-context-2.5.xsd/spring-spring-context-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/webflow-config/spring-webflow-config-1.0.xsd http://www.springframework.org/schema/webflow-config/spring-webflow-config-1.0.xsd/spring-spring-webflow-config-1.0.xsd-2.5.xsd
http://www.springframework.org/schema/jms/spring-jms-2.5.xsd http://www.springframework.org/schema/jms/spring-jms-2.5.xsd/spring-spring-jms-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/jee/spring-jee-2.5.xsd/spring-spring-jee-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd http://www.springframework.org/schema/lang/spring-lang-2.5.xsd/spring-spring-lang-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/osgi/spring-osgi.xsd http://www.springframework.org/schema/osgi/spring-osgi.xsd/spring-spring-osgi.xsd-2.5.xsd
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/tx/spring-tx-2.5.xsd/spring-spring-tx-2.5.xsd-2.5.xsd
http://www.springframework.org/schema/util/spring-util-2.5.xsd http://www.springframework.org/schema/util/spring-util-2.5.xsd/spring-spring-util-2.5.xsd-2.5.xsd
">
<bean id="sale01" class="application.common.entities.BidRoom">
<property name="itemId" value="0001"/>
<property name="lifeTime" value="15"/>
</bean>
</beans>
And I used the following code to create the sales:
ApplicationContext context = new FileSystemXmlApplicationContext(SalesManager.getSalesSourceFile());
SaleRoom saleRoom;
List<String> salesNames = new LinkedList<String>();
List<SaleRoom> allSales = new LinkedList<SaleRoom>();
// Get all sales id's for beans
NodeList salesNodeList = salesDoc.getElementsByTagName("bean");
for (int i = 0; i < salesNodeList.getLength(); i++) {
Node nNode = salesNodeList.item(i);
salesNames.add(((Element) nNode).getAttribute("id").toString());
}
for (String saleName : salesNames) {
if(saleName.contains("sale")) {
saleRoom = (SaleRoom) context.getBean(saleName);
allSales.add(saleRoom);
}
}
return allSales;
This is the new 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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy>
<aop:include name="logSettersCalls"/>
</aop:aspectj-autoproxy>
<bean id="logSettersCalls" class="application.logging.aop.LogSettersCalls"/>
<bean id="sale01" class="application.common.entities.BidRoom">
<constructor-arg index="0" type="int" value="0001"/>
<constructor-arg index="1" type="int" value="15"/>
</bean>
</beans>
The Aspect logging class:
#Aspect
public class LogSettersCalls {
#Pointcut("execution(void set*(*))")
public void setMethod() {}
#Before("setMethod()")
public void logSetterCall(JoinPoint theJoinPoint) {
String methodName = theJoinPoint.getSignature().getName();
Object newValue = theJoinPoint.getArgs()[0];
Object theObject = theJoinPoint.getTarget();
System.out.println("The method " + methodName + " is called on object "
+ theObject + " with the value " + newValue);
}
}
I'm using the same code for creating the beans via aop. and I get
Exception in thread "main" java.lang.ClassCastException: $Proxy11 cannot be cast to application.common.entities.SaleRoom
The line that throws the exception:
saleRoom = (SaleRoom) context.getBean(saleName);
Any help will be appreciated. Thanks.
Does your SaleRoom class implement some interface? If yes, then you should use interface and not class in you code:
ISaleRoom saleRoom = (ISaleRoom) context.getBean(saleName);
Because if your bean implements some interface then Spring by default will create proxy based on this interface.
Here is a good article about proxy creation in Spring.
Also you can change proxying mechanism for Spring AOP if you want to create proxy for target class. This is described here in reference documentation.

Unable to initiate a variable using #Value annotation, spring

My process class:
#Configurable("checkLicense")
public class CheckLicense {
String licensePath ;
#Value("${licenseKeyNotFound}")
String licenseKeyNotFound;
public boolean checkIn(String licensepath) {
System.out.println("hello "+licenseKeyNotFound);
licensePath = licensepath;
return checkIn();
}
}
My ApplicationContext.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class="com.smart.applicationlicense.CheckLicense"
scope="prototype">
</bean>
</beans>
Here is my properties file.
licenseKeyNotFound = License File Corrupted
Here is my servlet xml.
<context:property-placeholder location="conf/LicenseSettings.properties"
order="2" ignore-unresolvable="true" />
Eventhough I have used the #Configurable annotation along with the attributes Autowire.BY_NAME, Autowire.BY_TYPE, I am unable to initiate the variable of licenseKeyNotFound from the property file.
I was able to initiate the variable from a controller but not from this class which is declared #Configurable.
Can anyone please let me know what I am missing or what's wrong with my code?
Please let me know if there is something required from my code.
try this:
in your spring xml:
<context:property-placeholder location="classpath:your.properties" />
<context:load-time-weaver />
Try this
#Configurable
public class CheckLicense {
String licensePath;
String licenseKeyNotFound;
#Value("${licenseKeyNotFound}")
public void setLicenseKeyNotFound(String licenseKeyNotFound) {
this.licenseKeyNotFound = licenseKeyNotFound;
}
public boolean checkIn(String licensepath) {
System.out.println("hello " + licenseKeyNotFound);
licensePath = licensepath;
return checkIn();
}
}
in your properties file
licenseKeyNotFound=${value}

Categories