@Configuration
@Configuration就是以前spring的xml配置文件中的 的java实现,而@Bean就相当于
@Configuration+@Bean就实现了spring以前配置文件中的类的配置加载。
@Configurable
作用:
@Configurable作用在类上,一般情况下new 一个对象的时候并不会从spring容器中获取bean,而是直接调用类的构造函数进行实例化,为应对这种情况,@Configurable直接配置配置在自动装配的类上,即使调用方依然使用new 关键字创建对象,也会获取spring容器中的bean
最佳实践
Springboot中使用@Configurable
步骤
1、引入pom
org.springframework
spring-aspects
2、启动类添加注解
@EnableSpringConfigured
@EnableLoadTimeWeaving
3、添加jvm启动参数(重要)
在自己的maven仓库中找到jar包
-javaagent:/Users/ziliang.cao/env/repo/org/springframework/spring-instrument/5.1.9.RELEASE/spring-instrument-5.1.9.RELEASE.jar
代码如下:
import org.springframework.stereotype.Component;
@Component
public class MyRepository {
public void doSomething() {
System.out.println("xxx");
}
}
public class MyService {
@Autowired
private MyRepository myRepository;
public void doSomething() {
myRepository.doSomething();
}
}
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApiTest {
@Test
public void test() {
MyService myService = new MyService();
myService.doSomething(); // myRepository 会被自动注入
log.info("测试完成");
}
}
代码地址:
https://github.com/liangziccc/ddd-practice
如果失效可以 通过vx联系我:liangziccc2001