• 周四. 10 月 3rd, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

【java_ Basic insight] annotation injection configuration / properties read configuration / resourceb

King Wang

1 月 3, 2022

Annotation injection

/**
* Life cycle issues :
* The default life cycle of annotations is reserved to bytecode stage
* adopt Retention Meta annotation specifies the lifecycle of the annotation
* 1. SOURCE Keep it to the source phase
* 2. CLASS Keep to bytecode stage
* 3. RUNTIME Keep until run time
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface JdbcInfo {

String username() default "root"; // Set the default configuration , You can override 
String password();
String url();
String driverClassName() default "com.mysql.jdbc.Driver";
}
@JdbcInfo(password = "root", url = "jdbc:mysql:///practice")
public class JDBCUtil {

private static String url;
private static String user;
private static String password;
private static String driverClassName;
static {

//1. Gets the name... On the current class JDBCInfo The annotation object of 
Class clazz = JDBCUtil.class;
JdbcInfo jdbcInfo = (JdbcInfo) clazz.getAnnotation(JdbcInfo.class);
// Get the attribute values of the annotation object , It can be used later DriverManager Get database connection 
user = jdbcInfo.username();
password = jdbcInfo.password();
url = jdbcInfo.url();
driverClassName = jdbcInfo.driverClassName();
// Registration drive 
try {

Class.forName(driverClassName);
} catch (ClassNotFoundException e) {

e.printStackTrace();
}
}
}

Properties Reading configuration

 private static DataSource dataSource;
static {

// Create... From the factory class Druid Connection pool 
Properties properties = new Properties();
// The directory to get the classloader is src Catalog ,druidconfig.properties Should be in src Under the table of contents 
// When it exists resources Catalog , The directory also becomes classpath,druidconfig.properties You can also be in this directory 
InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("druidconfig.properties");
try {

properties.load(is);
} catch (IOException e) {

e.printStackTrace();
}finally {

try {

is.close();
} catch (IOException e) {

e.printStackTrace();
}
}
try {

// from properties File acquisition Druid Database connection pool 
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {

e.printStackTrace();
}
}

ResourceBundle Reading configuration

 // The file name is beans.properties, Note that the parameters are only filled in "beans"
ResourceBundle bundle = ResourceBundle.getBundle("beans");
String className = bundle.getString("className");

发表回复