Static method references non-static variable

1. Requirements description:

Call the database connection in the static method, and the parameters need to be obtained from the yml configuration file

2. Analysis of Doubtful Points

According to the conventional annotation @Value reference, it was found that the variable was always empty, and the data could not be obtained. Later, it was found that there was a problem with the variable reference

Three. Solve

1. @PostConstruct This annotation is used to modify a non-static void() method. The method modified by @PostConstruct will run when the server loads the Servlet, and will only be executed once by the server. PostConstruct is executed after the constructor and before the init() method.
2. Usually we will use @PostConstruct to annotate the execution order of the method in the entire Bean initialization in the Spring framework: Constructor (construction method) -> @Autowired (dependency injection) -> @PostConstruct (annotated method)

@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;
    }
}

Guess you like

Origin blog.csdn.net/yiye2017zhangmu/article/details/126385599