Spring6 IOC 全注解式开发

在这里插入图片描述

1. 依赖

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>6.1.14</version>
    </dependency>
    <!-- @Resource注解的依赖包,该注解是jdk提供的,不是spring的   -->
    <dependency>
      <groupId>jakarta.annotation</groupId>
      <artifactId>jakarta.annotation-api</artifactId>
      <version>3.0.0</version>
    </dependency>

2. 用注解类代替xml配置文件

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
// spring的全注解式开发
@Configuration
@ComponentScan({"org.example.service", "org.example.dao"})  // 指定要扫描的包
@ImportResource(locations = {"classpath:spring.xml"})	// 导入spring的XML配置文件(如果配置文件还需要导入时使用)
public class SpringConfig {
}

3. @Resource:非简单类型注入,官方推荐

@Service
public class StudentService {
      //  @Resource // 用法2:没有指定名字,先按属性名也就是studentDao查找,如果按属性名没有找到,就按属性类型查找
  	  @Resource(name = "studentByMySql")  // 用法1:指定名字
	  private StudentDao studentDao;
	  
	  public void save() {
	  	studentDao.save();
	}
}

4. 测试

@Test
public void testApp() {
	// 相当于读取xml文件,这条语句执行,代表创建了类的实例
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
    // 从bean池子中取出想要的实例对象
    StudentService studentService = applicationContext.getBean("studentService", StudentService.class);
    System.out.println(studentService);
    // 可以执行实例对象中的方法
    studentService.save();
}

5. 注解

  1. 类:
@Component

// @Component的别名:
@Controller //对Controller层类进行标注(主要接受处理URL)
@Service //对Service层的类进行标注(是进行业务处理)
@Repository //对DAO层实现类进行标注(和数据库打交道的类)
  1. 属性
@Value		// 简单类型注入
@Resource   // 非简单类型注入
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值