1. 首页
  2. 软件开发
  3. JAVA
  4. Spring-04-基于注解

Spring-04-基于注解

  • 发布于 2024-09-26
  • 1 次阅读

步骤:
1、在类上添加IoC注解
2、告诉Spring IoC容器,在哪些包下添加了IoC注解

@Component //通常描述Spring中的Bean
@Repository //通常访问层(Dao层)
@Controller //通常控制层
@Service //通常业务层

//@Scope(scopeName= ConfigurableBeanFactory.SCOPE_SINGLETON);    //单例 默认值
//@Scope(scopeName =ConfigurableBeanFactory.SCOPE_PROTOTYPE );    //多例
@Component  //相当于   <bean id="commomComponent" class="CommonComponent"></bean>

<!--
  base-package指定IoC容器的去哪些类下找注解类
-->
 <context:component-scan base-package="org.example"></context:component-scan>       //去org.example下找注解类

    //如果@Autowired下有多个组件会报错,可以使用@Qualifier(value="")获取bean的id
    @Autowired      //相当于<propertyname="" value=""></property>      不需要提供set方法
    @Qualifier(value="userServiceImpl2")

@Qualifier需要和@Autowired一起使用,如上面多个类继承同一个接口时

@Value注解,可以用于.properties文件下的内容

    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    //.properties文件
    jdbc.username=root
    jdbc.password=root

    //.xml配置引入
    <context:component-scan base-package="org.example.ioc_04"></context:component-scan>
    <context:property-placeholder location="jdbc.properties"></context:property-placeholder>

原文链接: https://blog.csdn.net/qq_53568730/article/details/135343026