spring纯注解开发模式

1、IOC的注解:

1.1 @Component【重点】:相当于<bean>标签:把对象交给spring管理,spring会帮助我们创建对象。

@controller,@Service,@Repository与@Component的作用完全一致,但更加详细化。

@Controller:用于web层的bean;

@Service:用于service层的bean;

@Repository:用于dao层的bean;

1.2其他注解【了解】

@scope:定义类的范围,更多是定义单例与多例。scope的常用值:singleton:单例,prototype:多例。

2、DI的注解:

1、@Comfiguration:标记这个类是一个配置类。

2、@ComponentScan:扫描包,扫描IOC与DI的注解。

3、@PropertySource:用来导入外部的properties文件。

4、@Import:用来导入配置子类或者其他普通类。

5、@Bean:打在方法上,spring会自动调用方法并获得返回值进行管理。

代码实现

springConfig
package dang.config;

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

//声明当前类为Spring配置类
@Configuration
//设置bean扫描路径,多个路径书写为字符串数组格式
@ComponentScan({"dang.service","dang.dao"})
public class SpringConfig {
}

bookDaoImpl
package dang.dao.impl;

import dang.dao.BookDao;
import org.springframework.stereotype.Repository;

//@Component定义bean
//@Component("bookDao")
//@Repository:@Component衍生注解
@Repository("bookDao")
public class BookDaoImpl implements BookDao {
    public void save() {
        System.out.println("book dao save ...");
    }
}
bookSERviceImpl
package dang.service.impl;

import dang.dao.BookDao;
import dang.service.BookService;
import org.springframework.stereotype.Service;

//@Component定义bean
//@Component
//@Service:@Component衍生注解
@Service
public class BookServiceImpl implements BookService {
    private BookDao bookDao;

    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    public void save() {
        System.out.println("book service save ...");
        bookDao.save();
    }
}
AppForAnnotation
import dang.config.SpringConfig;
import dang.dao.BookDao;
import dang.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AppForAnnotation {
    public static void main(String[] args) {
        //AnnotationConfigApplicationContext加载Spring配置类初始化Spring容器
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        BookDao bookDao = (BookDao) ctx.getBean("bookDao");
        System.out.println(bookDao);
        //按类型获取bean
        BookService bookService = ctx.getBean(BookService.class);
        System.out.println(bookService);
    }
}

posted @ 2023-07-13 16:01  当尖草北平铲  阅读(39)  评论(0)    收藏  举报