1 IOC 概念
- 控制反转:把创建对象的权利交给spring容器
- 之前的对象如何赋值:先new,再set
- 使用spring之后,对象由spring创建并保存到容器中,我们从spring容器中获取对象,并且由spring给对象进行赋值
- 总结:对象由spring创建并管理,我们从spring容器中获取需要的Bean对象就行了
2 扫描Bean
@Component 把普通类的对象交给spring管理,这些普通类不属于三层架构的类
@Controller 把控制器类交给spring管理
@Service 把业务层类交给Spring管理
@Repository 把数据访问层类交给spring管理(用的比较少,后面会与Mybits整合)
3 注意扫描包的位置![请添加图片描述](https://img-blog.csdnimg.cn/b258b80a47184a518d9bbd241540d56b.png)
要与相关类放在同级下,或者使用自定义扫描包的路径
4 管理第三方Bean
注意:如果要管理的对象来自于第三方,这时是无法用@Component等注解来实现的
解决方法:使用@Configuration+@Bean注解将返回的对象保存到Spring容器中
@Configuration //表示该类是一个配置类,有SpringBoot自动扫描加载
public class DataSourceConfig {
@Bean //默认添加到spring容器中Bean的名称就是方法名(首字母小写)
public DruidDataSource dataSource(){
//1 创建连接池对象
DruidDataSource dataSource=new DruidDataSource();
//2 设置连接参数
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/brand_demo?useSSL=false");
dataSource.setUsername("root");
dataSource.setPassword("root");
//3 返回连接池对象,保存到Spring容器中
return dataSource;
}
}
@Configuration:写在类上,表示该类是一个配置类,有SpringBoot自动扫描加载
@Bean:写在方法上,表示将该方法的返回值添加到Spring容器中,默认添加到spring容器中Bean的名称就是方法名(首字母小写)。
实现调用:在引导类中使用连接池
@SpringBootApplication//表示该类是SpringBoot程序入口
public class Spring01Application {
public static void main(String[] args) {
//1 返回值为Spring容器对象
ConfigurableApplicationContext ac = SpringApplication.run(Spring01Application.class, args);
//2 从Spring容器中获取DataSource连接池对象
DataSource dataSource = ac.getBean(DataSource.class);
//3 调用DataSource的getConnection()获取连接的方法
Connection conn=dataSource.getConnection();
System.out.println("conn = "+conn)
}
}
5 获取Bean对象的三种方法:
1 使用对象类型获取:UserService userService = app.getBean(UserService.class);最常用
2 使用方法名字获取: Data bean4 = (Date)app.getBean (“date”)
注:此时的方法为:@Bean
public Date date(){
return new Date();
}