Spring提供@Component注解的三个衍生注解
纯注解开发时不需要配置applictionContext.xml文件:
虽然不用xml文件定义,但是需要新建一个配置包,在里面配置bean:


在test文件中编写测试java程序实现注解依赖注入:
package test;
import com.Alvis.config.SpringConfig;
import com.Alvis.dao.BookDao;
import com.Alvis.service.BookService;
import com.Alvis.service.impl.BookServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App_01 {
public static void main(String[] args) {
// 配置文件
ApplicationContext apx = new AnnotationConfigApplicationContext(SpringConfig.class);
BookDao bookDao = (BookDao) apx.getBean("bookDao");
bookDao.run();
System.out.println("----------------------------------");
BookService bookService = (BookService) apx.getBean(BookServiceImpl.class);
bookService.run();
}
}
=============================================
this is BookDao......
----------------------------------
this is BookService......
this is BookDao......
进程已结束,退出代码0
如图所示:
在test文件中编写测试程序实现需求:
package test;
import com.Alvis.config.SpringConfig;
import com.Alvis.dao.BookDao;
import com.Alvis.service.BookService;
import com.Alvis.service.impl.BookServiceImpl;
import com.Alvis.service.impl.BookServiceImplCopy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App_01 {
public static void main(String[] args) {
// 配置文件
ApplicationContext apx = new AnnotationConfigApplicationContext(SpringConfig.class);
BookDao bookDao = (BookDao) apx.getBean("bookDao");
bookDao.run();
System.out.println("----------------------------------");
BookService bookService = (BookService) apx.getBean(BookServiceImplCopy.class);
bookService.run();
}
}
==========================================
this is BookDao......
----------------------------------
this is **Not** BookServiceCopy......
this is BookDao......
进程已结束,退出代码0
在配置类中定义配置注解@PropertySource:


在resources中配置值文件:
最后在test文件中编写Java程序实现需求:
package test;
import com.Alvis.config.SpringConfig;
import com.Alvis.service.InkService;
import com.Alvis.service.impl.InkServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App_02 {
public static void main(String[] args) {
// 获取配置类
ApplicationContext apx = new AnnotationConfigApplicationContext(SpringConfig.class);
InkService inkService =apx.getBean(InkServiceImpl.class);
inkService.run();
}
}
=====================================
this is InkService...
this is InkDao...
age: 100 name: "zhangsan"
进程已结束,退出代码0