Annotation injection
@Retention(RetentionPolicy.RUNTIME)
public @interface JdbcInfo {
String username() default "root";
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 {
Class clazz = JDBCUtil.class;
JdbcInfo jdbcInfo = (JdbcInfo) clazz.getAnnotation(JdbcInfo.class);
user = jdbcInfo.username();
password = jdbcInfo.password();
url = jdbcInfo.url();
driverClassName = jdbcInfo.driverClassName();
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Properties Reading configuration
private static DataSource dataSource;
static {
Properties properties = new Properties();
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 {
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
ResourceBundle Reading configuration
ResourceBundle bundle = ResourceBundle.getBundle("beans");
String className = bundle.getString("className");