为了简化Spring开发,从Spring3.0开始,新增了配置类,用@Configuration用于定义配置类,用于取代xml文件,可以进行全注解开发。
@Configuration类似xml中的
@bean类似xml中的
1.创建实体类
@Data@Componentpublic class User { //使用value给属性赋值 @Value("贾国辉") private String name;}2.创建配置类
//标记是配置类@Configuration //可以将这个理解成xml中的//扫描其他包@ComponentScan(basePackages = "com.jiaguohui.spring")//引入其他文件//@Import(User.class)//确定是否是单例模式@Scope("singleton")public class SpringConfig { //初始化方法,在构造函数后执行 @PostConstruct public void init(){ System.out.println("执行了初始化的方法"); } //销毁的方法,在销毁前执行 @PreDestroy public void destroy(){ System.out.println("执行了销毁的方法"); }} 解释说明:
1.使用@Configuration标记是一个配置类
2.使用@ComponentScan标记对包注解的扫描;
3.使用@Import引入多个配置文件
4.使用@Bean装配bean
5.使用@Scope标记是否是单例模式
6.使用@PostConstruct 在初始方法后,也就是init()方法
7.使用@PreDestroy表示在销毁前
8.使用@PropertySource引入配置文件,可以使用多个配置文件,但是不支持使用通配符
3.执行测试
@ExtendWith(SpringExtension.class)@ContextConfiguration(classes = SpringConfig.class)public class AppTest { @Test public void test2() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); User user = context.getBean("user", User.class); System.out.println("user = " + user); }}1.数据库配置类
@PropertySource({"jdbc.properties"})public class JdbcConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String user; @Value("${jdbc.password}") private String password; @Bean public DataSource getDataSource(){ DruidDataSource ds = new DruidDataSource(); ds.setDriverClassName(driver); ds.setUrl(url); ds.setUsername(user); ds.setPassword(password); return ds; } @Bean public Connection getConnection(@Autowired DataSource ds) { Connection conn = null; try { conn = ds.getConnection(); } catch (SQLException e) { throw new RuntimeException(e); } return conn; }}解释说明:
1.使用@PropertySource({"classpath:jdbc.properties"})读取配置文件
2.使用@Value("${driver}")读取配置文件的属性值
3.使用@Bean把对象交给Spring托管;
2.数据库配置文件
jdbc.driver=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatisjdbc.username=rootjdbc.password=root3.创建配置类
配置类可以使用@Import(JdbcConfig.class)引入其他配置文件
配置类可以使用@ComponentScan(basePackages = {"com.jiaguohui.spring"})进行包扫描
@Configuration //可以将这个理解成xml中的//扫描其他包@ComponentScan(basePackages = {"com.jiaguohui.spring"})//引入其他文件@Import(JdbcConfig.class)//确定是否是单例模式@Scope("singleton")public class SpringConfig { //初始化方法,在构造函数后执行 @PostConstruct public void init(){ System.out.println("执行了初始化的方法"); } //销毁的方法,在销毁前执行 @PreDestroy public void destroy(){ System.out.println("执行了销毁的方法"); }} @ExtendWith(SpringExtension.class)@ContextConfiguration(classes = SpringConfig.class)public class AppTest { @Test public void test01() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); Connection conn = context.getBean(Connection.class); System.out.println(conn); }} | 留言与评论(共有 0 条评论) “” |