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);
    }
}
相关推荐
Zzj_tju20 分钟前
Java 从入门到精通(六):抽象类与接口到底怎么选?
java·开发语言
@PHARAOH1 小时前
HOW - Go 开发入门(一)
开发语言·后端·golang
美好的事情能不能发生在我身上8 小时前
Hot100中的:贪心专题
java·数据结构·算法
myloveasuka8 小时前
Java与C++多态访问成员变量/方法 对比
java·开发语言·c++
Andya_net8 小时前
Spring | @EventListener事件机制深度解析
java·后端·spring
lang201509289 小时前
18 Byte Buddy 进阶指南:解锁 `@Pipe` 注解,实现灵活的方法转发
java·byte buddy
重庆小透明9 小时前
【java基础篇】详解BigDecimal
java·开发语言
无限大69 小时前
《AI观,观AI》:专栏总结+答疑|吃透核心,解决你用AI的所有困惑
前端·后端
小杍随笔9 小时前
【Rust 语言编程知识与应用:基础数据类型详解】
开发语言·后端·rust
毅航10 小时前
告别 AI 名词焦虑:一文读懂从 LLM 到 Agent Skill的演进
人工智能·后端