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);
    }
}
相关推荐
s***55817 分钟前
Skywalking介绍,Skywalking 9.4 安装,SpringBoot集成Skywalking
spring boot·后端·skywalking
lkbhua莱克瓦247 分钟前
集合进阶6——TreeMap底层原理
java·开发语言·笔记·学习方法·hashmap
JEECG低代码平台11 分钟前
GitHub 十大 Java 语言 AI 开源项目推荐
java·人工智能·github
小咖张15 分钟前
idea 启动失败,不加载自己的配置文件
java·ide·intellij-idea
m***119022 分钟前
使用IDEA环境编译Spring源码及spring源码调试环境搭建
java·spring·intellij-idea
代码程序猿RIP40 分钟前
【C++开发面经】全过程面试问题详解
java·c++·面试
whatever who cares41 分钟前
Java/Android中BigDecimal的相关操作
android·java·开发语言
IT_陈寒1 小时前
Redis深度优化:10个让你的QPS提升50%的关键配置解析
前端·人工智能·后端
烤麻辣烫1 小时前
黑马程序员苍穹外卖(新手) DAY3
java·开发语言·spring boot·学习·intellij-idea
妮妮喔妮1 小时前
JAVA反射的介绍(优缺点)
java·开发语言