Spring IOC——常用注解(Component)

常用注解

一、与xml对比

  1. 用于创建对象的:他们的作用就和在XML配置文件中编写一个标签 实现的功能是一样的
  2. 用于注入数据的:他们的作用就和在xml配置文件中的bean标签中写一个标签的作用是一 样的
  3. 用于改变作用范围的:他们的作用就和在bean标签中使用scope属性实现的功能是一样的
  4. 和生命周期相关的:他们的作用就和在bean标签中使用init- me thod和des troy - method的作用是一样的

二、 用于创建对象的注解

作用:就和在XML配文件中编写个标签实现的功能是一样的
Component:
作用:用于把当前类对象存入spring容器中
属性:
value:用于指定bean的id。当我们不写时,它的默认位是当前类名,且首字母改小写。

三、 代码

由于引用注解,需要更改xml中的beans,可以从 https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html 中按ctrl+F搜索xmlns:conn 复制其配置。(可以保存到书签,以后直接用)

package com.ay.service;

public interface AccountService {
    public  void saveAccount();
}

package com.ay.service.impl;

 import com.ay.service.AccountService;
 import org.springframework.stereotype.Component;

 import java.util.*;
@Component
public class AccountServiceImpl implements AccountService {
    @Override
    public void saveAccount() {
        System.out.println("方法创建了!");
    }
  
   
}

package com.ay.ui;

import com.ay.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean2.xml");
        AccountService as = (AccountService)ac.getBean("accountServiceImpl");
        as.saveAccount();
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <!--扫描包中所有的类,并把匹配的java类注册成Bean -->
   <context:component-scan base-package="com.ay"></context:component-scan>
</beans>
发布了9 篇原创文章 · 获赞 34 · 访问量 562

猜你喜欢

转载自blog.csdn.net/qq_44706044/article/details/104002684
今日推荐