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 "";
}
相关推荐
zzb15802 小时前
RAG from Scratch-优化-query
java·数据库·人工智能·后端·spring·mybatis
wuqingshun3141592 小时前
如何停止一个正在退出的线程
java·开发语言·jvm
Barkamin3 小时前
队列的实现(Java)
java·开发语言
骇客野人4 小时前
自己手搓磁盘清理工具(JAVA版)
java·开发语言
J2虾虾4 小时前
在SpringBoot中使用Druid
java·spring boot·后端·druid
清风徐来QCQ4 小时前
Java笔试总结一
java·开发语言
10Eugene4 小时前
C++/Qt自制八股文
java·开发语言·c++
程序员小假4 小时前
为什么要有 time _wait 状态,服务端这个状态过多是什么原因?
java·后端
kuntli5 小时前
p命名空间注入原理详解
spring
yuweiade5 小时前
【Spring】Spring MVC案例
java·spring·mvc