public class JDBC {
public final DataSource dataSource;
@Autowired
public JDBC(DataSource dataSource){
this.dataSource = dataSource;
}
}
spring:
datasource:
username: root
password: 6158
url: jdbc:mysql://localhost:3307/users?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
filters: stat,wall
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class JDBC {
public final DataSource dataSource;
@Autowired
public JDBC(DataSource dataSource){
this.dataSource = dataSource;
}
}
@Controller
public class MyController {
@Autowired
private JDBC jdbc;
@PostMapping(value = "/user/login")
public String login(){
//就可以使用已注入的JDBC对象了
return "redirect:/main";
}
}
@Autowired注解底层实现了单例模式,即多次注入的不同引用,会得到同一个对象
@Autowired
JDBC jdbc1;
@Autowired
JDBC jdbc2;
System.out.println(jdbc1 == jdbc2);
上述程序输入true
原文:https://www.cnblogs.com/seek-wind/p/13206416.html