1. bean作用范围注解配置
使用@Scope注解定义bean作用范围
1.1. singleton为单例
1.1.1 在bean头上使用@Scope注解,singleton
package com.lin.dao.impl;
import com.lin.dao.BookDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
@Repository
@Scope("singleton")
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("dao的save");
}
}
1.1.2 测试类创建容器获取俩个bean打印
package com.lin.app;
import com.lin.config.SpringConfig;
import com.lin.dao.BookDao;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
//1.创建spring容器,加载配置配置类
AnnotationConfigApplicationContext springContext = new AnnotationConfigApplicationContext(SpringConfig.class);
//2.根据类型获取bean
BookDao bookDao1 = springContext.getBean(BookDao.class);
BookDao bookDao2 = springContext.getBean(BookDao.class);
System.out.println(bookDao1);
System.out.println(bookDao2);
}
}
1.1.3运行结果
1.2 prototype,非单例
1.2.1 在bean头上使用@Scope注解,prototype
package com.lin.dao.impl;
import com.lin.dao.BookDao;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
@Repository
@Scope("prototype")
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("dao的save");
}
}
1.2.2 测试类创建容器依旧获取俩个bean打印
package com.lin.app;
import com.lin.config.SpringConfig;
import com.lin.dao.BookDao;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
//1.创建spring容器,加载配置配置类
AnnotationConfigApplicationContext springContext = new AnnotationConfigApplicationContext(SpringConfig.class);
//2.根据类型获取bean
BookDao bookDao1 = springContext.getBean(BookDao.class);
BookDao bookDao2 = springContext.getBean(BookDao.class);
System.out.println(bookDao1);
System.out.println(bookDao2);
}
}
1.2.3 运行结果观察
2. bean生命周期注解配置
2.1@PostConstruct、@PreDestroy定义bean生命周期
在bean中定义一个init方法,destroy,在该方法上使用该@PostConstruct、@PreDestroy注解;
package com.lin.dao.impl;
import com.lin.dao.BookDao;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Repository
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("dao的save");
}
public BookDaoImpl() {
System.out.println("Construct");
}
@PostConstruct
public void init(){
System.out.println("init...");
}
@PreDestroy
public void destroy(){
System.out.println("destroy...");
}
}
2.2 在测试类中创建容器,并注册关闭钩子或者直接关闭容器,运行
package com.lin.app;
import com.lin.config.SpringConfig;
import com.lin.dao.BookDao;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
//1.创建spring容器,加载配置配置类
AnnotationConfigApplicationContext springContext = new AnnotationConfigApplicationContext(SpringConfig.class);
springContext.registerShutdownHook();
}
}