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);
    }
}
相关推荐
JaguarJack8 分钟前
Laravel Go 高性能全栈框架发布
后端·go·laravel·服务端
钱栈up3 小时前
烧结趋势页台车速度曲线凭空消失:一次\\\"去重\\\"误杀的配置修复
后端·测试
刘小灰8 小时前
返璞归真,我开始更新博客了
前端·后端
一条Go9 小时前
巡检报告:把一次性排障变成可复跑的任务
后端·github
一条Go9 小时前
SQL 实验室:只读靠两把锁,DDL 靠模板
后端·github
一条Go9 小时前
维护窗口与升级策略:静默和升级怎么共存
后端·github
一条Go9 小时前
应用商店:版本、发布与部署为什么必须拆成三个阶段
后端·github
郝学胜-神的一滴10 小时前
Effective STL 条款15:注意字符串实现上的差异
java·开发语言·数据结构·c++·算法·visualstudio
sharemylove10 小时前
Java学习笔记 —— 面向对象专题
java·开发语言·笔记·学习·课程设计
京东云开发者10 小时前
一份数据,两种协议:京东云存储打通文件与对象
后端