阿里P8Java架构师谈:Spring注解开发

时间:2021-08-09
本文章向大家介绍阿里P8Java架构师谈:Spring注解开发,主要包括阿里P8Java架构师谈:Spring注解开发使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean。


@Scope("singleton") //singleton:标识单例模式,prototype:标识原型模式 、request:标识请求模式、session:标识会话模式 

xml 与注解:

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

    xml与注解最佳实践:

    • xml 用来管理bean;

    • 注解只负责完成属性的注入;

    • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持

      
      <!--指定要扫描的包,这个包下的注解就会生效-->
      
          <context:component-scan base-package="com.example.springannotation" />
      
          <context:annotation-config></context:annotation-config> 
      
      

JAVA的方式配置Spring

==================================================================================

  • @Configuration 这个也会spring容器托管,注册到容器中,因为他本来就是一个Component,

  • @Configuration代表这是一个配置类,就和我们之前看的beans.xml


// 配置类 代替 beans.xml

import com.example.springannotation.dao.Cat;

import com.example.springannotation.dao.People;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Import;



@Configuration

@ComponentScan("com.example.springannotation")

@Import(WwConfig.class)  //引入第二个配置

public class AppConfig {

    //注朋一个bean 相当于当于我们之前写的一个bean标签

    //这个方法的名字,就相当于bean标签中的id属性

    //这个方法的返回价,就和当了bean标签中的class属性

    @Bean

    public People getPeople(){

        return new People();

    }



    @Bean

    public Cat getCat(){

        return new Cat();

    }

}



import org.springframework.context.annotation.Configuration;

@Configuration

public class WwConfig {

} 

//测试类

import com.example.springannotation.config.AppConfig;

import com.example.springannotation.dao.People;

import org.junit.jupiter.api.Test;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

@SpringBootTest

class SpringannotationApplicationTests {

@Test

void contextLoads() {

    如果完全使用了配置类方式做,

    // 我们就只能通过 AnnotationConfig 上下文来获取容器,通过配置类的class对象加载!

    ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

    People people = (People) context.getBean("getPeople");

    System.out.println(people.toString());

最后

针对最近很多人都在面试,我这边也整理了相当多的面试专题资料,也有其他大厂的面经。希望可以帮助到大家。

下面的面试题答案都整理成文档笔记。也还整理了一些面试资料&最新2021收集的一些大厂的面试真题(都整理成文档,小部分截图),有需要的可以戳这里免费领取

最新整理电子书

原文地址:https://www.cnblogs.com/hgysvadavvc/p/15118654.html