Spring学习(二)

注解开发

注解开发bean

  • 给要放到容器的bean添加注解

    @Component("BookDao")
    public class BookDaoImpl implements BookDao {
    
        public void save() {
            System.out.println("Dao Save...");
        }
    }
    
  • 在xml中添加context

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
        <context:component-scan base-package="zk.dao.impl"/>
    </beans>
    
  • 如果在@component中不设定名称,那么getBean的时候就要通过类型.class来获取对象

DAO层,Service层和Controller层的写法,他们等价于Component

  • @Repository
  • @Service
  • @Controller

纯注解开发

  • 加载配置类

    @Configuration	// 配置类注解
    @ComponentScan("zk.dao.impl")	// 扫描包下的类
    public class SpringConfig {
    
    }
    
  • 修改main中的加载方式为注解加载

    public class App {
        public static void main(String[] args) {
            ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
            BookDao bookDao = (BookDao) applicationContext.getBean("BookDao");
            bookDao.save();
        }
    }
    

Bean管理

bean作用范围

  • 添加@Scope注解

    @Repository("BookDao")
    @Scope("singleton")
    public class BookDaoImpl implements BookDao {
    
        @Override
        public void save() {
            System.out.println("Dao save...");
        }
    }
    

bean生命周期

  • 在init函数上添加@Constructor注解
  • 在destroy函数上添加@PreDestroy注解

依赖注入

自动装配

  • @Autowired装配,不用写set方法
  • 按类型装配需要保证只有一个
  • 按名称装配用@qualifier
  • @Value为简单值注入

配置文件

  • 在resource中加入.properties配置文件
  • 在配置类上添加@PropertiesSource注解
  • @Value注解中用${}引用配置文件中的变量
  • 多配置文件使用数组的格式

第三方Bean

管理

前期用代码管理,后期spring boot感觉会搞定

注册

  • 新建一个Config类,在里面写获取对象的方法,加上@Bean注解
  • 在主Config类上添加@Import(新Config.class)注解

依赖注入

  • 简单类型直接拿成员变量 + @Value搞
  • 引用类型只能通过配置Bean搞,加个形参,引用容器中的Bean
posted @   Destiny233  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示