@Order注解可应用于类、方法和字段属性上;
@Order注解定义了Spring IOC容器中Bean的执行顺序的优先级,而不是定义Bean的加载顺序,Bean的加载顺序不受@Order或Ordered接口的影响(个人理解:在项目启动的时候会将所有的bean进行注入,注入后我们调用所需要的bean的先后顺序不会受到这@Order注解的影响)。
简单的应用:
package com.example.practice.service.impl;
import com.example.practice.service.IUserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements IUserService {
@Override
public void getUserInfo() {
System.out.println("成功获取用户信息");
}
}
package com.example.practice.service.impl;
import com.example.practice.service.ICarService;
import org.springframework.stereotype.Service;
@Service
public class CarServiceImpl implements ICarService {
@Override
public void getCarInfo() {
System.out.println("成功获取车辆信息");
}
}
package com.example.practice.anno;
import com.example.practice.service.impl.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
@Configuration
@Order(1)
public class AConfig {
@Bean
public UserServiceImpl aUserService() {
System.out.println("UserServiceImpl加载完成");
return new UserServiceImpl();
}
}
package com.example.practice.anno;
import com.example.practice.service.impl.CarServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
@Configuration
@Order(2)
public class BConfig {
@Bean
public CarServiceImpl aCarService() {
System.out.println("CarServiceImpl加载完成");
return new CarServiceImpl();
}
}
测试方法:
package com.example.practice.MainTest;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext("com.example.practice.anno");
}
}
运行结果为:
可见,@Order注解中的数字越小,优先级越高。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)