Bean基本注解开发

@Commponent

使用@Component注解代替<bean>标签

XML 复制代码
<!--注解扫描:扫描指定的基本包及其子包下的类,识别使用了@Component注解的文件-->
    <context:component-scan base-package="org.xfy"></context:component-scan>
java 复制代码
package org.xfy.Dao.Impl;

import org.springframework.stereotype.Component;
import org.xfy.Dao.UserDao;
//当注解的属性只有一个且为value的时候  在注解中value可以省略不写
@Component("userDao")
public class UserDaoImpl implements UserDao {
}

注意:@Component注解开发不指定id的话,那就是类名首字母小写

@Component注解开发不指定id的话,那就是类名首字母小写

@Service、@Componet 定义的 bean name 的生成规则如下: 优先取注解中的 value 指定的名字做为 bean name。 如果注解中没有指定的话,默认情况下是类名小写,例如: "mypackage.MyJdbcDao" -> "myJdbcDao" 注意有两种特殊的情况:

  1. 如果 bean 是内部类的话,因此将会是 "outerClassName.InnerClassName" 形式的名称

  2. 如果类名是连续2个首字母大写的话,bean name 就是类名,例如:"mypackage.MYJdbcDao" -> "MYJdbcDao"

@Bean 定义的 bean name 的生成规则是: 优先取注解中 name 指定的名字做为 bean name。 如果注解中没有指定的话,就取 methodName 做为 bean name。

java 复制代码
package org.xfy.Dao.Impl;

import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.xfy.Dao.UserDao;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

//当注解的属性只有一个且为value的时候  在注解中value可以省略不写
@Component("userDao")
@Scope(scopeName = "singleton")
@Lazy(value = false)
public class UserDaoImpl implements UserDao {
    public UserDaoImpl() {
        System.out.println("初始化");
    }
    @PostConstruct
    void init(){
        System.out.println("初始化方法");
    }
    @PreDestroy
    void destory(){
        System.out.println("销毁方法");
    }
}

其他注解

java 复制代码
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.stereotype;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}
相关推荐
可观测性用观测云5 小时前
Pyroscope Java 接入最佳实践
java
气π6 小时前
【JavaWeb】——(若依 + AI)-基础学习笔记
java·spring boot·笔记·学习·java-ee·mybatis·ruoyi
阿里云云原生6 小时前
AgentScope Java 1.0:从模型到应用,AI Agent 全生命周期管理利器!
java·云原生
running up6 小时前
Maven依赖管理和项目构建工具
java·maven
YDS8297 小时前
SpringCould —— 网关详解
后端·spring·spring cloud
老华带你飞7 小时前
列车售票|基于springboot 列车售票系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习·spring
java_logo7 小时前
LinuxServer.io LibreOffice 容器化部署指南
java·开发语言·docker·dubbo·openoffice·libreoffice·opensource
qq_589568107 小时前
@NotBlank与@NotEmpty注解无法导入
java·开发语言
李拾叁的摸鱼日常7 小时前
Spring Boot中OncePerRequestFilter原理与Filter单次调用控制全解析
java·后端
script.boy7 小时前
基于spring boot校园二手交易平台的设计与实现
java·spring boot·后端