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);
    }
}
相关推荐
曹牧9 分钟前
Java: Json的键值双引号
java·chrome·json
z***026011 分钟前
springboot整合modbus实现通讯
数据库·spring boot·后端
有一个好名字12 分钟前
Spring AI ——Java开发者的AI集成神器
java·人工智能·spring
i***683214 分钟前
Spring Boot--@PathVariable、@RequestParam、@RequestBody
java·spring boot·后端
p***950018 分钟前
Plugin ‘org.springframework.bootspring-boot-maven-plugin‘ not found的解决方法
java·maven
h***066528 分钟前
Spring Boot 集成 Kettle
java·spring boot·后端
n***840740 分钟前
Springboot-配置文件中敏感信息的加密:三种加密保护方法比较
android·前端·后端
旷野说1 小时前
如何用 Redpanda + 本地事务,实现“发消息 + 写 DB” 的强一致性!
java·数据库·kafka
unclecss1 小时前
从 0 到 1 落地 SSE:Spring Boot 3 实战 Server-Sent Events 推送全链路
java·spring boot·后端·http·sse
e***95641 小时前
springboot-自定义注解
java·spring boot·spring