静态类在初始化时注入参数

让spring通过注解的方式在初始化的时候给参数注入
1.  指定的类需要添加 @Component 让该类受spring管理
2.
@Autowired 需要注入的参数上加上该注解 让spring注入该参数
3.
@PostConstruct在初始化的方法上添加该注解,使静态类的参数在spring初始化时给静态参数初始化。
4.   实际代码案例如下:
@Component
public class WebSocketUtils {

    private static Logger logger = LoggerFactory.getLogger(WebSocketUtils.class);

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    private static SimpMessagingTemplate template;
    @PostConstruct
    public void init() {
        webSocketUtils  = this;
        WebSocketUtils.template = this.simpMessagingTemplate;
    }

}
在静态方法中,如果需要访问非静态的`studentMapper`并执行SQL操作,你需要确保该DAO对象已经被Spring管理并在其作用范围内。虽然静态方法不具备默认的@Autowired自动装配功能,但有几种方式可以让DAO注入到Spring容器中: 1. **构造函数注入**:如果你的`StudentMapper`类有构造函数接收`StudentDao`作为参数,可以在调用静态方法的地方传入已经由Spring管理的DAO实例。 ```java // 示例代码 public static void initializeData(StudentDao studentDao) { // 使用已注入的studentDao } ``` 然后,在调用这个静态方法的地方通过`ApplicationContext`获取DAO实例: ```java @Autowired private ApplicationContext context; public static void main(String[] args) { StudentDao dao = context.getBean(StudentDao.class); initializeData(dao); } ``` 2. **Singleton模式**: 将`StudentMapper`包装在一个单例类中,内部持有DAO的实例,这样在静态方法中就可以直接使用。 ```java public class DaoWrapper { private static final DaoWrapper INSTANCE = new DaoWrapper(); private StudentDao studentDao; @Autowired private DaoWrapper(StudentDao studentDao) { this.studentDao = studentDao; } public static StudentMapper getInstance() { return INSTANCE.studentMapper; } } // 在静态方法中使用 DaoWrapper.getInstance().executeSql() ``` 3. **AOP(切面编程)**:如果允许引入AOP,可以创建一个Advisor,将DAO注入到特定的静态方法上。 ```java @Aspect @Component public class StaticMethodAspect { @Before("execution(* com.example.staticmethod.*(..))") public void injectDao(JoinPoint joinPoint) { Object target = joinPoint.getSignature().getDeclaringType(); // 获取静态方法,注入DAO } } ``` 在这个例子中,你需要配置AOP代理来代理静态方法以便在调用注入DAO。 选择哪种方式取决于你的具体需求和项目结构。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值