java ImportResource注解

ImportResource用于加载资源文件,用于将变量注解。

拥有变量的类

package com.imooc.beanannotation.javabased;

public class MyDriverManager {
	
	public MyDriverManager(String url, String userName, String password) {
		System.out.println("url : " + url);
		System.out.println("userName: " + userName);
		System.out.println("password: " + password);
	}

}

注解类,将资源文件中的变量注入类成员

添加注解的类

package com.imooc.beanannotation.javabased;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;

@Configuration
@ImportResource("classpath:config.xml")
public class StoreConfig {
	
	@Value("${url}")
	private String url;

	@Value("${jdbc.username}")
	private String username;

	@Value("${password}")
	private String password;

	@Bean
	public MyDriverManager myDriverManager() {
		return new MyDriverManager(url, username, password);
	}
}

加载classpath下的config.xml文件,将url,username,password等变量注入成员变量

config.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="classpath:/config.properties"/>
    
</beans>

config.properties

#Created by JInto - www.guh-software.de
#Sun Aug 10 16:25:57 CST 2014
jdbc.username=root
password=root
url=127.0.0.1

测试方法

	@Test
	public void testMyDriverManager() {
		MyDriverManager manager = super.getBean("myDriverManager");
		System.out.println(manager.getClass().getName());
	}

使用注解和使用XML配置文件对比

使用注解和使用XML配置文件

使用注解和使用配置文件2

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部