Spring注解开发

🎊🎊️️🚸🛳️

注解开发定义bean

🎊🎊️️🎊🎊️️
➠使用@Component定义bean

@Component ("bookDao")
public class BookDaoImpl implements  BookDao{
}
@Component
public class BookServiceImpl  implements BookService{
        }     

核心配置文件中通过组件扫描加载bean

<context:component-scan base-package="com.GY"/>

🎊🎊️️🎊🎊️️
Spring提供@Component注解的三个衍生注解

@Controller:用于表现层bean定于
@Service:用于业务层bean定义
@Repository:用于数据层bean定义

纯注解开发(使用Java类代替配置文件,开启了Spring快速开发赛道)

bean的配置
在这里插入图片描述

配置类

package config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

//代表配置类(用于设定当前类为配置类)
@Configuration
//扫描注解(用于设定扫描路径,此注解只能添加一次,多个数据需用数组格式)
@ComponentScan("com.GY")
public class SpringConfig {
}

配置类的加载
在这里插入图片描述
TIP:(扫描多个数据时需用数组格式)
🚸🚸🚸
在这里插入图片描述eg:

//代表配置类
@Configuration
//扫描注解
@ComponentScan({"com.GY","com.GY.service"})
public class SpringConfig {
}

Bean管理

bean作用范围

●单例

@Repository
@Scope("singleton")

●非单例(不同对象)

@Repository
@Scope("prototype")

在这里插入图片描述

bean生命周期使用 @PostConstruct @PreDestroy定义bean生命周期

@PostConstruct    //构造方法后
    public void put() {
        System.out.println("初始化前.......");
    }
@PreDestroy       //在销毁前
    public void out() {
        System.out.println("销毁前........");
    }

在这里插入图片描述

依赖注入

🍹🍭 🍹🍭 🍹🍭
使用 @Autowired 注解开启自动装配模式
注意 : 自动装配基于反射设计创建对象并暴力反射对应属性为私有属性初始化数据,因此无需提供setter方法
注意 : 自动装配建议使用无参构造方法创建对象(默认),如果不提供对应构造方法,请提供唯一的构造方法

@Service
public class BookServiceimpl implements BookService{
    @Autowired      //自动装配
    private BookDao bookDao;
    
    @Override
    public void save() {
        System.out.println("BookService........");
        bookDao.save();
    }
}

🚸🚸🚸
(如果在注入时,有多个相同类型的bean,使用@Qualifier指定对应加载的bean的名称)

@Service
public class BookServiceimpl implements BookService{
    @Autowired
    //进行自动装配的情况下指定对应加载的bean的名称
    @Qualifier("bookDao1")
    private BookDao bookDao;

    @Override
    public void save() {
        System.out.println("BookService........");
        bookDao.save();
    }
}

●使用@Value实现简单类型的注入

@Repository
    public class BookDaoimpl implements BookDao{
@Value("1")
    private int age;
    }

注解开发总结

xml配置与注解配置比较
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

new一个对象_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值