静态方法引用非静态变量

一.需求描述:

在静态方法里面调用数据库连接,参数需要从yml配置文件获取

二.疑点解析

按常规注解@Value引用,发现变量一直为空,获取不到数据,后来发现变量引用有问题

三.解决

1.@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
2.通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序:Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)

@Component
public class ProcUtils {
	
	@Value("${spring.datasource.url}")
	private String url;
	private static String dbUrl;

	@Value("${spring.datasource.username}")
	private String username;
	private static String dbName;
	
	@Value("${spring.datasource.password}")
	private String password;
	private static String dbPassword;
	
	@Value("${spring.datasource.driver}")
	private String driver;
	private static String dbDriver;

	private static Connection connection = null;

	public static Connection getConnection(){
		try {
			Class.forName(dbDriver);
			connection = DriverManager.getConnection (dbUrl,dbName,dbPassword);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}

	@PostConstruct
	public void setProfile() {
		dbUrl = this.url;
		dbName = this.username;
		dbPassword = this.password;
		dbDriver = this.driver;
    }
}

猜你喜欢

转载自blog.csdn.net/yiye2017zhangmu/article/details/126385599