1、@Component:放在类上,把普通类实例化到spring容器中。可以说很多注解都是基于这个注解的。
2、@Bean: 放在方法上,用@Bean标注方法等价于XML中配置bean,这个方法一般返回一个实体对象,告诉spring这里产生一个对象,然后这个对象会交给Spring管理。产生这个对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的容器中。
3、@Configuration:标注当前类是配置类,并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到srping容器中,并且实例名就是方法名。
package com.ahies.stm.app.config;
/**
* Created by Administrator on 2018/8/5 0005.
*/
import com.corundumstudio.socketio.*;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
@org.springframework.context.annotation.Configuration
public class IMServerConfiguration {
@Value("${stm.server.port}")
private Integer port;
@Value("${stm.server.threads}")
private String threads;
private SocketIOServer server ;
@Bean
public SocketIOServer socketIOServer() throws NoSuchAlgorithmException, IOException
{
Configuration config = new Configuration();
config.setPort(port);
int workThreads = !StringUtils.isBlank(threads) && threads.matches("[\\d]{1,6}") ? Integer.parseInt(threads) : 100 ;
config.setWorkerThreads(workThreads);
config.getSocketConfig().setReuseAddress(true);
config.getSocketConfig().setSoLinger(0);
config.getSocketConfig().setTcpNoDelay(true);
config.getSocketConfig().setTcpKeepAlive(true);
return server = new SocketIOServer(config);
}
@Bean
public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
return new SpringAnnotationScanner(socketServer);
}
@PreDestroy
public void destory() {
server.stop();
}
}
4、@ConfigurationProperties:将配置文件中的参数映射成一个对象,通过prefix来设定前缀,然后将后面的和对象的属性名一致就能实现注入(当然这个对象需要注入的属性需要提供get和set方法 - - - 因为spring底层其实就是通过反射调用该对象的set方法)
@ConfigurationProperties(prefix = “spring.datasource.test1”)
public class Datasource1 {
private String url;
private String username;
private String password;
get - - set方法
}
application.properties:
spring.datasource.test1.url=jdbc:mysql://localhost:3306/multipledatasource1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.test1.username=root
spring.datasource.test1.password=root
spring.datasource.test1.driver-class-name=com.mysql.cj.jdbc.Drive