注解方式

配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="org.example"/>
</beans>

添加注解@Component

@Component("bookDao")
public class BookDaoImpl implements BookDao {


    @Override
    public void save() {
        System.out.println("bookDao...");
    }
    public void init(){
        System.out.println("init...");
    }
    public void destroy(){
        System.out.println("destroy...");
    }
}

纯注解开发

去掉配置文件,加上注解类

package org.example.Spring;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
@ComponentScan("org.example")
public class Spring {
}

加载注解类

package org.example;

import org.example.Spring.Spring;
import org.example.dao.BookDao;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class APP2 {
    public static void main(String[] args) {
////        getBookDao getBookDao = new getBookDao();
////        BookDao bookDao = getBookDao.getBookDao();
////        bookDao.save();
//        ClassPathXmlApplicationContext ctx= new ClassPathXmlApplicationContext("applicationContext.xml");
//        BookDao bookDao = (BookDao) ctx.getBean("bookDao");
//        bookDao.save();
//        //ctx.close();//比较暴力 不能放在创建对象前
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Spring.class);
        BookDao bookDao = (BookDao) ctx.getBean("bookDao");
        bookDao.save();
    }
}

控制bean的注解

@scope:控制bean的作用范围

@PostConstruct:init方法

@PreDestory:destory方法

 

posted @ 2023-02-17 22:22  会秃头的小白  阅读(12)  评论(0编辑  收藏  举报