@Bean
用于Spring自动注入创建对象创建对象,如如果方法,带参数,则参数必须也是使用了@Bean注解创建的对象
类的起始需要注解@Configuration和@Component
@Configuration
public class SparkShellConfiguration {
@Bean
// @Bean(name="spark")
/**
* @Autowired
* KerberosSparkProperties spark,
*/
public KerberosSparkProperties kerberosSparkProperties() {
return new KerberosSparkProperties();
}
@Bean
public SparkShellProcessManager processManager(final SparkShellProperties sparkShellProperties, final KerberosSparkProperties kerberosProperties,
@Qualifier("sparkLoginUsers") final Optional<Properties> users) {
if (sparkShellProperties.getServer() != null) {
return new ServerProcessManager(sparkShellProperties);
} else if (!users.isPresent()) {
throw new IllegalArgumentException("Invalid Spark configuration. Either set spark.shell.server.host and spark.shell.server.port in spark.properties or add the auth-spark Spring profile"
+ " to application.properties.");
} else if (sparkShellProperties.isProxyUser()) {
return new MultiUserProcessManager(sparkShellProperties, kerberosProperties, users.get());
} else {
return new DefaultProcessManager(sparkShellProperties, kerberosProperties, users.get());
}
}
}
创建好后,可以使用@Resource和@Autowired注解调用已经注解的类,不能使用new ....调用
@PropertySouce
@PropertySouce是spring3.1开始引入的基于java config的注解。
通过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。
@Configuration
// 有该注解会默认使用prefix+类的字段,如:email.from去匹配
@ConfigurationProperties(prefix = "email", ignoreUnknownFields = false)
@PropertySource(value={"classpath:email.properties"},encoding="utf-8")
public class EmailProperty {
private String from;
private String clientPassWord;
private String port;
private String ipAddress;
private String server;
// setter、getter......
}
@Profile
@Profile的作用是把一些meta-data进行分类,分成Active和InActive这两种状态,然后你可以选择在active 和在Inactive这两种状态 下配置bean,在Inactive状态通常的注解有一个!操作符,通常写为:@Profile("!p"),这里的p是Profile的名字
spring.profiles.active 用来设置哪些profile被激活
spring.profiles.include 属性用来设置无条件的激活哪些profile
java -jar test.jar --spring.profiles.active=dev
@ConditionalOnProperty
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {
String[] value() default {}; //数组,获取对应property名称的值,与name不可同时使用
String prefix() default "";//property名称的前缀,可有可无
String[] name() default {};//数组,property完整名称或部分名称(可与prefix组合使用,组成完整的property名称),与value不可同时使用
String havingValue() default "";//可与name组合使用,比较获取到的属性值与havingValue给定的值是否相同,相同才加载配置
boolean matchIfMissing() default false;//缺少该property时是否可以加载。如果为true,没有该property也会正常加载;反之报错
boolean relaxedNames() default true;//是否可以松散匹配
}
该注解能够控制某个configuration是否生效。具体操作是通过其两个属性name以及havingValue来实现的,其中name用来从application.properties中读取某个属性值,如果该值为空,则返回false;如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。如果返回值为false,则该configuration不生效;为true则生效。