Spring @Value 使用

昨天看到项目里一个Config类,加载一个properties文件,通过IO流去读取并加载到Property类里,感觉太过复杂,印象中有Spring @Value标签可以使用,就研究了一下。


目的:使用@Value来注入配置在properties文件中的key-value,使用@Value必须是托管在spring ioc容器中的bean


方法:你可以直接使用@Value注入全局变量,也可以注入setter方法


碰到的问题:我在注入controller类的时候,注入失败,注入其它类可以,原因是没有在web.xml->Spring的DispatcherServlet->contextConfigLocation指定的xml中配置PropertySourcesPlaceholderConfigurer


相关代码:


xml:

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:spring_*.properties</value>
            </list>
        </property>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>

也可以使用@Configurable @PropertySource,来使用一个配置类替换XML

package com.smith.config;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;
@Configurable

@PropertySource("classpath:spring_test.properties") 
public class SmithConfig {
	
	
	
}


Properties:在Maven项目下resource下建一个spring_开头的properties文件


Controller类:


package com.smith.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.smith.config.SmithConfig;

@Controller
@RequestMapping("/helloSmith")
@Import(SmithConfig.class)
public class PropertyController {
	
	@Value("${abc}")
    private String abc;
	/*
	@Autowired
    private SmithConfig config;*/
	@RequestMapping(value="/showProperty", method = { RequestMethod.POST, RequestMethod.GET })
    public void showCardNoPage() {
	
		System.out.println(abc);
		
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值