【Spring】核心概念:注解开发 Bean 作用范围 & 生命周期

新博客:https://blog.bigdataboy.cn/article/445.html

Bean 作用范围

直接一个直接就搞定 @Scope("singleton")

import cn.bigdataboy.dao.NameDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Repository
@Scope("singleton") // prototype / singleton (默认)
public class NameDaoImpl implements NameDao {

    public void getName() {
        System.out.println("getName: bigdataboy");
    }
}

生命周期

直接一个直接就搞定,@PostConstruct (初始化之后),@PreDestroy (在销毁前)

import cn.bigdataboy.dao.NameDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Repository
public class NameDaoImpl implements NameDao {

    public void getName() {
        System.out.println("getName: bigdataboy");
    }

    @PostConstruct  // 初始化之后
    public void init() {
        System.out.println("init running ...");
    }

    @PreDestroy // 在销毁前
    public void destroy() {
        System.out.println("destroy running ...");
    }

}

mark

案例代码:https://pan.bigdataboy.cn/s/pvJcR

发表评论 / Comment

用心评论~