Spring @Configuration注解使用示例

x33g5p2x  于2022-09-24 转载在 Spring  
字(10.5k)|赞(0)|评价(0)|浏览(232)

Spring @Configuration 在类级别进行了注解,以指示一个类声明了一个或多个 @Bean 方法,并且可以由 Spring 容器处理以在运行时为这些 bean 生成 bean 定义和服务请求。 @Configuration 可以与其他 Spring 注解一起使用。查找与 @Configuration 结合使用的一些注解。
@PropertySource:为向 Spring 的环境添加属性源提供了一种方便且声明性的机制。
@Profile:允许在指定配置文件处于活动状态时注册配置类。
@EnableScheduling:启用 Spring 的计划任务执行能力。
@ImportResource:表示一个或多个包含要导入的 bean 定义的资源。
@Import:表示要导入的一个或多个 @Configuration 类。
@ComponentScan:配置组件扫描指令以与 @Configuration 类一起使用。
@EnableWebMvc:提供 Spring MVC 配置。
@EnableWebSecurity:提供 Spring Security 配置。

在此页面上,我们将提供一些示例来创建和使用 @Configuration 类。

@Configuration

我们将创建一个用 @Configuration 注解的类,我们将在这个类中使用 @Bean 注解创建一个 bean。
AppConfig.java

package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
	 @Bean
	 public User getUser() {
		 return new User("Mahesh");
	 }
}

在上面的 JavaConfig 中,我们创建了一个 User 类 bean。找到这门课。
User.java

package com.concretepage;
public class User {
	private String userName;
	public User(String userName) {
		this.userName = userName;
		System.out.println("--- Initializing User ---");
	}
	public String getUserName() {
		return userName;
	}
}

我们可以使用 AnnotationConfigApplicationContext 或通过 Spring <beans> XML 访问 @Configuration 类。

1. 使用 AnnotationConfigApplicationContext 访问 @Configuration 类:
要注册使用 @Configuration 注解的配置类,我们可以使用 AnnotationConfigApplicationContext,它使用构造函数、register()scan() 方法注册类。在构造函数和 register() 中,我们指定配置类,在 scan() 中,我们指定包名。 scan() 将扫描指定的包及其子包。
MySpringApp.java

package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MySpringApp {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
		User user = ctx.getBean(User.class);
		System.out.println("User name: " + user.getUserName());
		ctx.registerShutdownHook();
		ctx.close();		
	}
}

输出

--- Initializing User ---
User name: Mahesh

2. 通过 Spring <beans> XML 访问 @Configuration 类:
@Configuration 类可以通过 Spring <beans> XML 注册,如下所示。
app-config.xml

<?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 
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">

	<context:annotation-config/>
        <bean class="com.concretepage.AppConfig"/>
</beans>

MySpringAppWithXML.java

package com.concretepage;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MySpringAppWithXML {
	public static void main(String[] args) {
		AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("app-config.xml");
		User user = ctx.getBean(User.class);
		System.out.println("User name: " + user.getUserName());
		ctx.registerShutdownHook();
		ctx.close();		
	}
}

@Configuration + @Autowired

我们可以在 @Configuration 类中使用 @Autowired 注入外部化值和其他 bean。在我们的示例中,我们将注入 Spring Environment
AppConfig.java

package com.concretepage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class AppConfig {
	 @Autowired Environment env;	
	 
	 @Bean
	 public User getUser() {
		 System.out.println(env.getProperty("java.home"));
		 return new User("Mahesh");
	 }
}

@Configuration + @PropertySource

@PropertySource 提供了一种方便的声明机制,用于将属性源添加到 Spring 的环境中。要从 @Configuration 类中的属性文件中读取属性,我们使用 @PropertySource 注解。在我们的示例中,我们将使用 @PropertySource 读取属性文件并使用 @Value 注解读取值。
找到我们示例的属性文件。
myproject.properties

cp.user.country= USA
cp.user.role= ADMIN

找到配置类。
AppConfig.java

package com.concretepage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:myproject.properties")
public class AppConfig {
	 @Value("${cp.user.country}")
	 private String country;

	 @Value("${cp.user.role}")
	 private String role;
	 
	 @Bean
	 public User getUser() {
		 System.out.println("Country: "+ country);
		 System.out.println("Role: "+ role);		 
		 return new User("Mahesh");
	 }
}

输出

Country: USA
Role: ADMIN
--- Initializing User ---
User name: Mahesh

@Configuration + @Profile

我们可以将 Spring @Profile@Configuration 一起使用。 @Profile 允许在指定配置文件处于活动状态时注册配置类。
在我们的示例中,我们有两个配置类,一个具有 prod 配置文件,另一个具有 dev 配置文件。
ProdEnvConfig.java

package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import com.concretepage.User;

@Configuration
@Profile("prod")
public class ProdEnvConfig {
  @Bean
  public User getUser(){
	return new User("Prod User");
  }
}

DevEnvConfig.java

package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import com.concretepage.User;

@Configuration
@Profile("dev")
public class DevEnvConfig {
   @Bean
   public User getUser(){
      return new User("Dev User");
   }
}

我们可以使用 ConfigurableEnvironmentsetActiveProfiles() 方法激活配置文件。
MySpringApp.java

package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MySpringApp {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.getEnvironment().setActiveProfiles("dev");
		ctx.scan("com.concretepage");
		ctx.refresh();
		User user = ctx.getBean(User.class);
		System.out.println("User name: " + user.getUserName());
		ctx.registerShutdownHook();
		ctx.close();
	}
}

在上面的代码中,我们激活了 dev 配置文件,因此应用程序将使用 DevEnvConfig 配置类。
输出

--- Initializing User ---
User name: Dev User

@Configuration + @EnableScheduling

我们可以将 Spring @EnableScheduling@Configuration 一起使用。 @EnableScheduling 启用了 Spring 的计划任务执行能力。
使用 @Scheduled 注解查找具有计划任务的类。
Task.java

package com.concretepage;
import org.springframework.scheduling.annotation.Scheduled;
public class Task {
	@Scheduled(fixedRate = 2000)
	public void doTask() {
		System.out.println("Work in progress...");
	}
}

找到用 @EnableScheduling 注解的配置类。
AppConfig.java

package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
public class AppConfig {
	@Bean
	public Task task() {
		return new Task();
	}
}

MySpringApp.java

package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MySpringApp {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
	}
}

输出

Work in progress...
Work in progress...
Work in progress...

@Configuration + @ImportResource

我们可以将 Spring @ImportResource@Configuration 一起使用。 @ImportResource 注解指示一个或多个包含要导入的 bean 定义的资源。
在我们的示例中,我们将创建一个 XML 配置,然后我们将使用 @ImportResource 将其导入 @Configuration 类。
app-config.xml

<?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 
           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="com.concretepage.User">
        <constructor-arg name="userName" value="Mahesh"/>
    </bean>
</beans>

AppConfig.java

package com.concretepage;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource("app-config.xml")
public class AppConfig {
}

MySpringApp.java

package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MySpringApp {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
		User user = ctx.getBean(User.class);
		System.out.println("User name: " + user.getUserName());
		ctx.registerShutdownHook();
		ctx.close();
	}
}

输出

--- Initializing User ---
User name: Mahesh

@Configuration + @Import

我们可以将 Spring @Import@Configuration 一起使用。 @Import 指示要导入的一个或多个 @Configuration 类。
在我们的示例中,我们有两个 @Configuration 类,一个配置类正在使用 @Import 注解导入另一个配置类。
OtherAppConfig.java

package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OtherAppConfig {
	@Bean
	public User getUser() {
		return new User("Mahesh");
	}
}

AppConfig.java

package com.concretepage;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(OtherAppConfig.class)
public class AppConfig {
}

MySpringApp.java

package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MySpringApp {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
		User user = ctx.getBean(User.class);
		System.out.println("User name: " + user.getUserName());
		ctx.registerShutdownHook();
		ctx.close();
	}
}

输出

--- Initializing User ---
User name: Mahesh

@Configuration + @ComponentScan

我们可以将 Spring @ComponentScan@Configuration 一起使用。 @ComponentScan 注解配置组件扫描指令以与 @Configuration 类一起使用。
在我们的示例中,我们有一个使用 @Component 类注解的组件,该组件将由在配置类中注解的 @ComponentScan 扫描。
AppConfig.java

package com.concretepage;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.concretepage")
public class AppConfig {
}

User.java

package com.concretepage;
import org.springframework.stereotype.Component;

@Component
public class User {
	private String userName = "Mahesh";
	public String getUserName() {
		return userName;
	}
}

MySpringApp.java

package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MySpringApp {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
		User user = ctx.getBean(User.class);
		System.out.println("User name: " + user.getUserName());
		ctx.registerShutdownHook();
		ctx.close();
	}
}

输出

User name: Mahesh

相关文章