[spring]spring注解开发

8.使用注解开发

1.bean

spring4以后,注解依赖于aop包,确保你的lib中有它

[spring]spring注解开发

确保开启了使用注解


2.组件代替bean实现自动注入

在配置文件中自动扫描包下的所有类为bean


在类对象上加上注解@Component可以被扫描

  • @component (把普通pojo实例化到spring容器中,相当于配置文件中的 )
@Component

使用注解给属性注入值

package pojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author panglili
 * @create 2022-07-24-9:52
 */
@Component
public class People {
    private String name;
    @Value("123")
   public int age;
    private Dog dog;
    private Cat cat;
 }
}
  • 但是复杂的属性配置还是建议使用xml统一管理注入

3.component衍生的注解

dao:@repository

service:@service

controller:@controller

跟component功能相同只是能够使得分工更加的明确

小结:

xml与注解:

  • xml更加万能,适用于各种场合!维护简单方便
  • 注解 不是自己类使用不了,维护相对复杂

最佳实践:

  • xml用来管理bean
  • 注解只负责属性的注入

Original: https://www.cnblogs.com/lumanmanqixiuyuanxi/p/16521990.html
Author: 路漫漫qixiuyuanxi
Title: [spring]spring注解开发

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/619537/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球