复杂对象的注入

1. 书写Component类

  • Component类就是你希望被注入的Java类
public class JDBC {
    
    public final DataSource dataSource;

    @Autowired
    public JDBC(DataSource dataSource){
        this.dataSource = dataSource;
    }
}
  • 优先将@Autowired注解写在构造器函数上,因为类加载器优先使用构造器为成员变量赋值,其次才为@Autowired变量注入值。

2. 书写YML注入文件

  • 在这个文件中,为所要注入的变量赋值
spring:
  datasource:
    username: root
    password: 6666
    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

3. 为Component类添加注解

@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class JDBC {
    
    public final DataSource dataSource;

    @Autowired
    public JDBC(DataSource dataSource){
        this.dataSource = dataSource;
    }
}

4. 在Controller中调用Component类并添加注解

@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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值