日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Spring中@Bean注解的作用以及如何使用

作者:小孫小孫夢想成真 更新時間: 2022-08-13 編程語言

@Bean

在spring中,將組件注入ioc容器的方式通常分為兩種

  1. 第一種也就是我們常用的@Component@Controller@ServicResponse以及@Respository注解。
  2. 使用@Bean注解來注入組件。
    兩種方式的區(qū)別:
  • @Component注解作用于類上,而@Bean注解作用于配置類中的某一個方法上;
  • @Component表明告知Spring為當前的這個類創(chuàng)建一個bean,而@Bean表明告知Spring此方法將會返回一個對象,將返回的對象注入到容器中。
  • @Bean注解的使用更加靈活。

如何使用?

在沒有了解@Bean注解之前,相信大家都是以這種方式創(chuàng)建對象的:

    
    @AllArgsConstructor
    @NoArgsConstructor
    @Component
    public class User {
        private String name;
        private Integer age;
    }

然后直接通過@Autowired從容器中取出該對象

	@Autowired
	private User user

同樣的場景,來使用@Bean試試。

    @Configuration
    public class MyConfiguration {
        @Bean
        public User user() {
            return new User();
        }
    }

該注解必須要在標有@Configuration的配置類中使用才會有效。
上述代碼表示,將@Bean注解修飾的方法的返回值注入到IOC容器中。

	@Autowired
	private User user

通過上述幾段代碼,你可能很難發(fā)現(xiàn)@Bean注解靈活在哪里,反而還要作用在配置類中,更麻煩!

使用場景

場景1: 有時候我們需要根據(jù)條件來注入組件。

    @Configuration
    public class MyConfiguration {
        @Bean
        public User user() {
        	int i = 10;
        	if(i < 7) {
        		return new User("jack", 20);
      		} else {
      			return new User("david", 18);
      		}
        }
    }

場景2: 想象一下如果我們需要使用外部引入的lib中的組件時怎么辦?使用@Component注解標注到別人的源碼上面?顯然這是不現(xiàn)實的,這個時候@Bean就可以發(fā)揮其優(yōu)勢了。

	@Configuration
    public class MyConfiguration {
        @Bean
        public ArrayList<User> list() {
            ArrayList<User> list = new ArrayList<>();
            list.add(new User("nacy", 17));
            return list;
        }
    }

使用@Bean注解在實際項目中解決的問題

在微服務(wù)的兩個模塊,其中模塊A作為公共模塊,模塊B(SpringBoot模塊)導(dǎo)入了模塊A的Maven依賴(dependency),在項目運行時只啟動模塊B,模塊A相當于一個靜態(tài)的公共模塊,不會去使用SpringBoot啟動它。

模塊A:

  • 配置類:
    @Configuration
    @EnableWebSecurity  // 開啟Security
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    	@Autowired
    	private EmployeeRolePath employeeRolePath;
    	
        @Override
        protected void configure(HttpSecurity http) throws Exception {
     		List<String> uri = employeeRolePath.getUri();
        }
    
  • EmployeeRolePath:
    	@Component
    	@ConfigurationProperties("role.employee.path")
    	public class EmployeeRolePath {
    	
    	    private List<String> uri;
    	
    	    public List<String> getUri() {
    	        return uri;
    	    }
    	
    	    public void setUri(List<String> uri) {
    	        this.uri = uri;
    	    }
    	}
    

模塊B:

  • 配置類,繼承了模塊A的配置類
    	@Configuration
    	@EnableWebSecurity  // 開啟Security
    	public class SecurityConfig extends WebSecurityConfig {
    			// ........
    			// .........
    	}
    
  • yml配置文件:
    role:
      admin:  # 需要admin權(quán)限的訪問路徑
          path:
            uri:
              - /admin/adminRole/**
      employee: # 需要employee權(quán)限的訪問路徑
          path:
            uri:
              - /admin/category/**
              - /admin/dish/**
              - /admin/flavor/**
              - /admin/setmeal/**
    

先說一下我要實現(xiàn)的功能:要使上述yaml配置文件中的配置成功綁定到EmployeeRolePath類中并生效。

很顯然,上述代碼肯定不會生效,原因就是我們啟動模塊B時,Spring只能夠掃描到本模塊中的配置類SecurityConfig,以及它繼承模塊A中的配置類WebSecurityConfig,而作用在EmployeeRolePath類上的注解是不可能為生效的,原因就是模塊A根本沒啟動,沒有人去掃描他,它只是一個靜態(tài)的模塊而已。

解決:

在模塊A的配置類中使用@Bean注解注入EmployeeRolePath組件。

	@Configuration
	@EnableWebSecurity  // 開啟Security
	public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	    @Override
	    protected void configure(HttpSecurity http) throws Exception {
	 		List<String> uri = employeeRolePath().getUri();
	    }
	    
	    @Bean
	    public EmployeeRolePath employeeRolePath() {
	        return new EmployeeRolePath();
	}

如上述在本配置類中要使用該組件,直接調(diào)用employeeRolePath()就能獲取到容器中的EmployeeRolePath組件了。

為什么這樣可以生效?
上述說了,當模塊B啟動時,會先初始化加載模塊B的配置類,而模塊B的配置類又繼承了模塊A的配置類,所以Spring是能夠掃描到模塊A中的配置的,并且它們是在同一個IOC容器中的,所以在模塊B中定義的配置文件也會生效。

原文鏈接:https://blog.csdn.net/sunao1106/article/details/126305955

欄目分類
最近更新