一、@Scope
1、@Scope注解是springIoc容器中的一个作用域
2、Spring IoC 容器中具有以下几种作用域:基本作用域singleton(单例)、prototype(多例),Web 作用域(reqeust、session、globalsession),自定义作用域
常用的是:singleton(单例)、prototype(多例)
3、使用默认的@Scope
package com.gg.dao.impl;
import com.gg.dao.BookDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
/**
* @Author: {LZG}
* @ClassName: BookDaoImpl
* @Description: TODO
* @Date: 2022/4/25 18:19
**/
@Repository("bookDao")
@Scope
public class BookDaoImpl implements BookDao {
@Override
public void save() {
System.out.println("book dao save");
}
}
测试
package com.gg;
import com.gg.config.SpringConfig;
import com.gg.dao.BookDao;
import com.gg.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @Author: {LZG}
* @ClassName: App
* @Description: TODO
* @Date: 2022/4/25 18:18
**/
public class App2 {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
// 使用id获取
BookDao bookDao = (BookDao) context.getBean("bookDao");
BookDao bookDao2 = (BookDao) context.getBean("bookDao");
System.out.println(bookDao);
System.out.println(bookDao2);
}
}
?测试结果
?4、使用prototype(多例)
给@Scope设置作用域
?测试结果
?二、Bean的生命周期
@PostConstruct:这个注解是由Java提供的,它用来修饰一个非静态的void方法。它会在服务器加载Servlet的时候运行,并且只运行一次。
@PreDestroy:@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前。执行顺序如下所示。
package com.gg.dao.impl;
import com.gg.dao.BookDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* @Author: {LZG}
* @ClassName: BookDaoImpl
* @Description: TODO
* @Date: 2022/4/25 18:19
**/
@Repository("bookDao")
public class BookDaoImpl implements BookDao {
@Override
public void save() {
System.out.println("book dao save");
}
@PostConstruct
void init(){
System.out.println("初始化.....");
}
@PreDestroy
void destroy(){
System.out.println("销毁");
}
}
package com.gg;
import com.gg.config.SpringConfig;
import com.gg.dao.BookDao;
import com.gg.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @Author: {LZG}
* @ClassName: App
* @Description: TODO
* @Date: 2022/4/25 18:18
**/
public class App2 {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
// 使用id获取
BookDao bookDao = (BookDao) context.getBean("bookDao");
System.out.println(bookDao);
context.close();
}
}
执行结果
?
|