Spring-1-注解管理依赖

可以将 Spring  其当做一个 容器 ,可以随意的存储对象。

@Component
@Controller
@Service
@Repository

这四个是常用的注解,用于声明 Bean 的注解,可以在后面跟括号为起 value 属性传值,代表依赖注入的 id,若不设置,则默认为 类名首字母小写
这四个注解本质都是同一个注解 @Component,只是名称不同,可以用于三层架构中不同的层
写在需要注入依赖的类上

上面是写在类上的注解

接下来是写在属性或者方法上的注解

@Value ()

给简单属性直接赋括号里的值

@AutoWired  

非简单类型注入,默认根据类型装配,byType
@Autowired+@Qualifier 连用可以根据名字装配,byName
使用方法,在被注入的类上要加 @Compoment 注解
在注入类的非简单属性类型上直接写上 @Autowired 即可自动工具类型装配
当被注入的对象有多个,就无法通过类型直接注入,需要使用名字:
@Autowired
@Qualifier("被注入依赖的id")
两个注解联合使用
Autowired 注解可以使用在,属性,构造方法,构造方法的传参等需要注入依赖处

@Resource

未指定 name 属性则直接根据当前属性名作为名字
该方法与 @Autowired+@Qualifier 连用 的效果一致
区别:不能出现在构造方法上

使用前,需要注入依赖,配置 sping.xml



    4.0.0

    org.example
    Compomen
    1.0-SNAPSHOT

    
    
        
        
            repository.spring.milestone
            Spring Milestone Repository
            https://repo.spring.io/milestone
        
    

    

        
            org.springframework
            spring-context
            6.0.0-M2
        

        
            junit
            junit
            4.13.2
            test
        

        
            jakarta.annotation
            jakarta.annotation-api
            2.1.1
        
    

    
        17
        17
    

需要对要用到的包进行扫描,在 spring.xml 中声明 (在 resource 目录下创建)




    

需要注入对象的类:

@Component
public class Compomen {

    @Value("18")
    int age;

    @Autowired
    Auto auto;

    @Resource(name="reso")
    Reso reso;

    public void printValue(){
        System.out.println(age);
    }

    public void autoIsNullOrNot(){
        System.out.println(auto == null ? "fail":"succeed");
    }

    public void printReso(){
        reso.ResoText();
    }

}

被注入的两个类:

@Component("reso")
public class Reso {
    public void ResoText(){
        System.out.println("Reso这个类中的方法被调用");
    }
}
@Component
public class Auto {
    Auto(){
        System.out.println("Auto类中的构造方法被调用...");
    }
}

测试程序

    @Test
    public void text(){
        //拿到配置文件中的容器
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        //拿到容器中的类
        Compomen compomen = context.getBean("compomen", Compomen.class);
        compomen.printValue();
        compomen.autoIsNullOrNot();
        compomen.printReso();
    }

运行结果:

Auto类中的构造方法被调用...
18
succeed
Reso这个类中的方法被调用

Process finished with exit code 0

扩展:@AutoWired 和 @Resoutce 注解可以给接口对象注入依赖,在底层,若该接口有实现类,则会在容器中自动寻找实现类。故我们只需给实现类打上 @Compoment 而无需给 接口 打注解

你可能感兴趣的:(java后端转后厨,spring,java,后端)