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 "";
}
相关推荐
qq_185198694 小时前
(Spring Bean + delegateExpression)实现http服务 的完整可运行项目
spring
小Ti客栈4 小时前
Spring Boot 集成 Springdoc-OpenAPI 与 Knife4j实现接口文档与可视化调试
java·spring boot·后端
Ai拆代码的曹操5 小时前
Spring 事务 REQUIRES_NEW 嵌套调用:连接池翻倍的秘密
java·后端·spring
动恰客流统计5 小时前
ReID边缘计算视觉统计:餐饮店客流增长的数字化破局路径
java·大数据·运维·人工智能
Ivanqhz6 小时前
Rust &‘static str浅析
java·前端·javascript·rust
weixin_419658319 小时前
Docker 搭建 Jenkins 服务
java·docker·jenkins
captain3769 小时前
多线程线程安全问题
java·java-ee
CoderYanger9 小时前
A.每日一题:1979. 找出数组的最大公约数
java·程序人生·算法·leetcode·面试·职场和发展·学习方法
灵极海10 小时前
LangChain4j RAG 实战完整指南:从入门到踩坑
java·langchain
yaoxin52112310 小时前
476. Java 反射 - 调用方法
java·开发语言