Spring之注解开发

1.使用Java类代替xml配置文件

在自定义的Java类上加@Configuration注解,表示设定当前类为配置类

java 复制代码
package config;

import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringConfig {
}

2.使用@Component注解定义bean

(1)在相应的Java类上加@Component注解,表示这是一个bean

java 复制代码
package domain;

import org.springframework.stereotype.Component;

@Component
public class Animal {
    private String name;
    private int age;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

注:单独使用@Component注解相当于在xml文件只写了<bean>标签的class属性,@Component("animal")相当于在xml文件写了<bean>标签的id和class两个属性
(2)Spring提供了@Component注解的三个衍生注解

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

3.使用@ComponentScan注解使配置类能扫描到定义的bean

在配置类上加@Configuration注解,使其能扫描到定义的bean

java 复制代码
@Configuration
@ComponentScan("com.example.domain")
public class SpringConfig {
}

注:@ComponentScan注解用于设定扫描路径,此注解只能添加一次,多个路径需使用数组格式

java 复制代码
@ComponentScan({"com.example.service","com.example.domain"})

4.通过AnnotationConfigApplicationContext类获取IoC容器

java 复制代码
import config.SpringConfig;
import domain.Animal;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Demo {
    public static void main(String[] args) {
    	ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        Animal animal = ctx.getBean(Animal.class);
        System.out.println(animal);
    }
}
相关推荐
AnAnCode6 小时前
ECS 架构 (Entity Component System) - 数据导向编程快速入门
java·架构·游戏服务器
qq_12498707536 小时前
基于SpringBoot+vue的小黄蜂外卖平台(源码+论文+部署+安装)
java·开发语言·vue.js·spring boot·后端·mysql·毕业设计
小二·6 小时前
Spring框架入门:TX 声明式事务详解
java·数据库·spring
i02086 小时前
Java 17 + Spring Boot 3.2.5 使用 Redis 实现“生产者–消费者”任务队列
java·spring boot·redis
烤麻辣烫6 小时前
黑马程序员苍穹外卖后端概览
xml·java·数据库·spring·intellij-idea
代码与野兽6 小时前
AI交易,怎么让LLM自己挑选数据源?
前端·javascript·后端
天天摸鱼的java工程师7 小时前
JDK 25 到底更新了什么?这篇全景式解读带你全面掌握
java·后端
毕设源码-邱学长7 小时前
【开题答辩全过程】以 个人博客网站为例,包含答辩的问题和答案
java
非鱼feiyu7 小时前
自关联数据表查询优化实践:以 Django + 递归 CTE 构建树结构为例
数据库·后端·django
零日失眠者7 小时前
这5个Python库一旦掌握就离不开
后端·python