一、使用@interface关键字来标识为注解类:
@Target({ ElementType.TYPE })
@Retention( RetentionPolicy.RUNTIME )
@Component
public @interface Config {
}
@Target({ ElementType.TYPE })为注解的作用目标 这里表示的是作用为接口、类、枚举、注解
@Retention( RetentionPolicy.RUNTIME )为在运行时通过反射获取字节码文件中的注解
@Component 这个是spring的注解,作用为实例化到spring的容器中,相当于配置文件中的bean
二、配置文件: XXX.properties
username:hezhiyu
pwd:123456
三、创建普通类,使用自定义注解,使用@Value注解 属性名要和properties中定义的属性名一致(注意)
@Config
public class Constant {
@Value("${username}")
private String username;
@Value("${pwd}")
private String pwd;
get...
set..
}
四、使用方式:在controller 或者imp中 自动注入进来@Autowired和@Resource都可以
@Autowired
private Constant constant;
constant.getXxx;
sout(constant.getXxx);
这样就能读取到配置的信息了,通过自定义注解可以
当然需要加载资源文件:
<context:property-placeholder
ignore-unresolvable="true"location="classpath:xx.properties" />
这样也可以:
<bean id="propertyBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<array><value>classpath:config/*.properties</value>
</array>
</property>
</bean>