Skip to content

Latest commit

History

52 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

mini-spring

实现 AnnotationConfigApplicationContext

实现 AnnotationConfigApplicationContext 注解容器,实现以下功能:

  • 解析配置@Configuration注解
  • 实现包扫描@ComponentScan注解
  • 解析方法上上@Bean注解
  • 解析配置文件@PropertySource注册
  • 解析@Component注解,解析@Service
@Configuration@PropertySource("classpath:person.properties")
@ComponentScan(basePackages = {"org.springframework.test.configuration"})
publicclassAppConfig {
@Bean(name = "aa")
publicAa() {
returnnewA();
}
@Bean(name = "myCar", initMethod = "initMethod", destroyMethod = "destroyMethod")
publicCarcar() {
returnnewCar("BMW", "red");
}
}
@Component("myPerson")
publicclassPerson {
@Value("${name}")
privateStringname;
@Value("${age}")
privateIntegerage;
// getter and setter...
}
/** * @author cuzz * @date 2022/3/16 22:20 */@Service("myUserService")
publicclassUserServiceImplimplementsUserService {
@AutowiredprivatePersonperson;
@OverridepublicStringgetUseName() {
returnperson.getName();
}
}
publicclassConfigurationTest {
@TestpublicvoidtestAnnotationConfig() throwsException {
AnnotationConfigApplicationContextapplicationContext = newAnnotationConfigApplicationContext(AppConfig.class);
Map<String, Car> beansMap = applicationContext.getBeansOfType(Car.class);
for (Map.Entry<String, Car> stringCarEntry : beansMap.entrySet()) {
System.out.println("beanName: " + stringCarEntry.getKey() + " bean: " + stringCarEntry.getValue());
}
UserServicebean = applicationContext.getBean(UserService.class);
System.out.println(bean);
applicationContext.close();
}
}

打印结果:

Car customInitMethod...
beanName: myCar bean: Car{name='BMW', color='red'}
org.springframework.test.configuration.UserServiceImpl@3439f68d
Car customDestroyMethod...
publicclassConfigurationTest {
@TestpublicvoidtestServiceAnnotation() throwsException {
AnnotationConfigApplicationContextapplicationContext = newAnnotationConfigApplicationContext(AppConfig.class);
Map<String, UserService> beansMap = applicationContext.getBeansOfType(UserService.class);
for (Map.Entry<String, UserService> stringUserServiceEntry : beansMap.entrySet()) {
System.out.println("beanName: " + stringUserServiceEntry.getKey() + " bean: " + stringUserServiceEntry.getValue());
}
}
}

打印结果:

beanName: myUserService bean: org.springframework.test.configuration.UserServiceImpl@dbd940d

参考

About

参考Spring简单实现的注解功能

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages