1第一步:当然要有自己的配置文件例如:db.properties 里面有个jdbc.username = root
2第二步:在spring配置文件里 扫描文件夹,读取配置文件到spring容器
<
3第三部:注入到属性
package com.mj.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class UserServiceImpl {
@Value("${jdbc.username}")
String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "UserServiceImpl{" +
"name='" + name + ''' +
'}';
}
}
第四部:单元测试
import com.mj.service.UserServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
private ApplicationContext ctx;
@Before
public void before(){
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void run(){
System.out.println("=====单元测试=====");
UserServiceImpl userService = (UserServiceImpl) ctx.getBean("userServiceImpl");
System.out.println(userService.getName());
}
}
第四部:查看log输出
=====单元测试=====
root