1:@Autowired注入
import lombok.Data;//第一种方法的配置
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "jdbc")
public class jdbcproperties {
private String driverClassName;
private String url;
private String username;
private String password;
}
//第一种方法的设置
package HMH.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.JdbcProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@EnableConfigurationProperties(jdbcproperties.class)
@Configuration//声明一个类是一个Java配置类,相当于xml配置文件
public class JDBCConfigration {
@Autowired
private jdbcproperties jdbcproperties;
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(this.jdbcproperties.getDriverClassName());
dataSource.setUrl(this.jdbcproperties.getUrl());
dataSource.setUsername(this.jdbcproperties.getUsername());
dataSource.setPassword(this.jdbcproperties.getPassword());
return dataSource;
}
}
2:构造方法注入
3:@Bean方法形参注入
4:注解在@Bean方法上使用@ConfigurationProperties(prefix = "jdbc")
//第四种
package HMH.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "jdbc")
public class jdbcproperties {
private String driverClassName;
private String url;
private String username;
private String password;
}
//第四种
package HMH.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.JdbcProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@EnableConfigurationProperties(jdbcproperties.class)
@Configuration//声明一个类是一个Java配置类,相当于xml配置文件
public class JDBCConfigration {
@Bean
@ConfigurationProperties(prefix = "jdbc")
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
return dataSource;
}
}
第四种更新简单,但是有局限性,因为要有get方法,一般都用第一种
重点掌握的注解: