org.springframework.beans.TypeMismatchException when using @Value annotation

1. Problem Description.

After I added @Value annotation to inject properties value in a POJO, when I started the application server and access a page, encountered this error:

Could not autowire field: private int com.company.system.module.service.AccountControlConfiguration.bookieDefault; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "${frequency.bookie.default}"

Properties file:

frequency.bookie.default = 1000
frequency.1.default = 1000
frequency.2.default = 500
frequency.2.placeorder = 100
frequency.2.fetchodd = 100
frequency.2.bethistory = 100
frequency.2.betlist = 100
frequency.2.balance = 100
frequency.2.betstatus = 100
frequency.5.default = 1000
frequency.27.default = 1000
frequency.18.default = 1000
applicationContext-service.xml

<context:property-placeholder location="classpath*:configuration.properties" />
POJO:

@Component
public class AccountControlConfiguration {

	@Value("${frequency.bookie.default}")
	private int bookieDefault;

		
	@PostConstruct
	public void test(){
		System.out.println("Injected Successfully: " + bookieDefault);
	}

2. Analysis

At first, I checked the variable spelling and the properties file path, and other details, no joy in the end.

Second round, I added a post construct method as shown previously, with this method, I saw that the injection works fine during Jetty start. Then, I guess spring framework tries to instantiate this bean twice.

So, I checked all application context files, and I found that 2 application context files include this line which would impact our AccountControlConfiguration:

<context:component-scan base-package="com.company.system.*.service"></context:component-scan>
In addition, I added the <context:property-placeholder> in just one application context file, therefore, I got the NumberFormatException.

3. Solution

Comment out redundant <context:component-scan> declaration.

4. Lesson

Be careful when add <context:component-scan>, don't repeat them in different files, which would cause unpleasant unexpected errors.





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值