当前位置: 首页 > news >正文

Spring 学习日记 day2

目录

6.核心容器

7.注解式开发

7.1使用注解代替 的配置

7.2纯注解开发

7.3注解式依赖注入

7.4第三方bean管理

8.Spring整合MyBatis


6.核心容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//这个容器创建方式是立即加载bean
 Resource resources = new ClassPathResource("applicationContext.xml");
        BeanFactory bf = new XmlBeanFactory(resources);
        BookDao bookDao = bf.getBean(BookDao.class);
        bookDao.save();
//而这个容器创建方式为延迟加载bean
7.注解式开发
7.1使用注解代替<bean> 的配置
//在BookDaoImpl上添加@Component("参数") 这里的参数是可配可不配的
//如果配,在使用时 getbean("参数")
//如果不配,在使用时则 getbean (接口名.class)
//在applicationContext.xml 中添加扫描
  <context:component-scan base-package="com.scidag"/>
  
//对于@Component注解,还衍生出了其他三个注解`@Controller`、`@Service`、`@Repository` ,这几个注解作用是完全一样的,只是为了区分这个类是属于表现层,业务层还是数据层
7.2纯注解开发
//取消了applicationContext.xml文件,取而代之的是一个java类
//在这个类上添加注解
@Configuration
@ComponentScan("com.scidag")//这个就是相当于xml中的扫描
7.3注解式依赖注入
名称@Scope
类型类注解
位置类定义上方
作用设置该类创建对象的作用范围 可用于设置创建出的bean是否为单例对象
属性value(默认):定义bean作用范围, ==默认值singleton(单例),可选值prototype(非单例)==
名称@PostConstruct
类型方法注解
位置方法上
作用设置该方法为初始化方法
属性
名称@PreDestroy
类型方法注解
位置方法上
作用设置该方法为销毁方法
属性

@Autowired
放在参数上
- @Autowired是按照类型注入的,给BookDao的两个实现起了名称,它还是有两个bean对象,为什么不报错?
​
- @Autowired默认按照类型自动装配,如果IOC容器中同类的Bean找到多个,就按照变量名和Bean的名称匹配。因为变量名叫`bookDao`而容器中也有一个`booDao`,所以可以成功注入。
​
​
分析下面这种情况是否能完成注入呢?
 @Autowired
    private BookDao bookDao;
@Repository("bookDao2")
public class BookDaoImpl2 implements BookDao {    
@Repository("bookDao1")
public class BookDaoImpl implements BookDao {    
- 不行,因为按照类型会找到多个bean对象,此时会按照`bookDao`名称去找,因为IOC容器只有名称叫`bookDao1`和`bookDao2`,所以找不到,会报`NoUniqueBeanDefinitionException`
​
此时使用@Qualifier("bookDao1")
@Qualifier注解后的值就是需要注入的bean的名称。
注意:@Qualifier不能独立使用,必须和@Autowired一起使用

简单数据类型注入 (@Value ("值"))

读取配置文件

在配置类添加注解@PropertySource("文件名")

在@Value中读取配置文件内容,使用${属性名}

7.4第三方bean管理

单独一个config类获取的第三方bean的方法加注解@Bean

在Spring中引入使用@Import(config类.class)

8.Spring整合MyBatis
  • 导入依赖

    <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.2.21.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.16</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.6</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>5.2.10.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.3.0</version>
            </dependency>
        </dependencies>
  • 编写Dao

     @Insert("insert into tbl_account(name,money)values(#{name},#{money})")
        void save(Account account);
        @Delete("delete from tbl_account where id = #{id} ")
        void delete(Integer id);
        @Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")
                void update(Account account);
        @Select("select * from tbl_account")
        List<Account> findAll();
        @Select("select * from tbl_account where id = #{id} ")
        Account findById(Integer id);
  • 编写 实体类对应数据库中的表,。。。

  • 编写service的实现类,在里面完成Dao类的自动类型装配

    @Service
    public class AccountServiceImpl implements AccountService {
        @Autowired
        private AccountDao accountDao;
        @Override
        public void save(Account account) {
            accountDao.save(account);
        }
    ​
        @Override
        public void delete(Integer id) {
            accountDao.delete(id);
        }
    ​
        @Override
        public void update(Account account) {
            accountDao.update(account);
        }
    ​
        @Override
        public List<Account> findAll() {
            return accountDao.findAll();
        }
    ​
        @Override
        public Account findById(Integer id) {
            return accountDao.findById(id);
        }
  • 数据源的配置类

     @Value("${jdbc.driver}")
        private String driver;
        @Value("${jdbc.url}")
        private String url;
        @Value("${jdbc.username}")
        private String userName;
        @Value("${jdbc.password}")
        private String password;
        @Bean
        public DataSource dataSource(){
            DruidDataSource ds = new DruidDataSource();
            ds.setDriverClassName(driver);
            ds.setUrl(url);
            ds.setUsername(userName);
            ds.setPassword(password);
            return ds;
        }
  • mybatis配置类

      @Bean
        public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
            SqlSessionFactoryBean ssfb=new SqlSessionFactoryBean();
            ssfb.setTypeAliasesPackage("com.scidag.domain");
            ssfb.setDataSource(dataSource);
            return  ssfb;
        }
        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer(){
            MapperScannerConfigurer msc=new MapperScannerConfigurer();
            msc.setBasePackage("com.scidag.dao");
            return msc;
        }
  • 主配置类

    @Configuration  //
    @ComponentScan("com.scidag")
    @PropertySource("classpath:jdbc.properties")
    @Import({JdbcConfig.class,MybatisConfig.class})
    public class SpringConfig {
    }
    ​
  • 主程序App.java

     AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfig.class);
            AccountService bean = ac.getBean(AccountService.class);
            List<Account> all = bean.findAll();
            all.forEach(account -> System.out.println(account));

8.2整合junit

  • 依赖

    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.10.RELEASE</version>
    </dependency>
  • /设置类运行器
    @RunWith(SpringJUnit4ClassRunner.class)
    //设置Spring环境对应的配置类
    @ContextConfiguration(classes = {SpringConfiguration.class}) //加载配置类
    //@ContextConfiguration(locations={"classpath:applicationContext.xml"})//加载
    配置文件
    public class AccountServiceTest {
    //支持自动装配注入bean
    @Autowired
    private AccountService accountService;
    @Test
    public void testFindById(){
    System.out.println(accountService.findById(1));
    }
    @Test
    public void testFindAll(){
    System.out.println(accountService.findAll());
    }
    }

相关文章:

  • 使用fastapi部署stable diffusion模型
  • 如何记录Matlab程序运行过程中所占用的最大内存(续)
  • 天梯赛 L2-005 集合相似度
  • 配置 VSCode 的 C# 开发环境
  • 山寨币ETF的叙事,不灵了?
  • 【css酷炫效果】纯CSS实现全屏粒子连线
  • sparksql的Transformation与 Action操作
  • 解决git init 命令不显示.git
  • 3.1 在VisionPro脚本中添加CogGraphicLabel
  • LeetCode 热题 100_跳跃游戏(78_55_中等_C++)(贪心算法)
  • 技术路线图ppt模板_流程图ppt图表_PPT架构图
  • 购物车全选功能
  • Api架构设计--- HTTP + RESTful
  • C++和标准库速成(八)——指针、动态数组、const、constexpr和consteval
  • dataframe数据形式操作中的diff和shift函数区别与对比
  • 自交互学习:计算病理学中用于分子特征预测的多尺度组织形态学特征的融合与演化|文献速递-医学影像人工智能进展
  • 3.git操作:git init说明
  • macOS 安装 LibreOffice
  • QPS和TPS 的区别是什么?QPS 大了会有什么问题,怎么解决?
  • 数据库设计实验(4)—— 数据更新实验
  • 上海与世界|黄菊与上海建设中国式全球城市
  • 杨轶群任莆田市荔城区人民政府副区长
  • 马上评|科学谋划“十五五”,坚定不移办好自己的事
  • 光明网评“泉州梦嘉商贸楼不到5年便成危楼”:监管是否尽职尽责?
  • 这就是上海!
  • 澎湃回声|山东莱州、潍坊对“三无”拖拉机产销市场展开调查排查