@Autowired
use
Usually within a class, another class is needed. @autoWired finds the corresponding component in the container based on the type and then inject it.
test
Configure package scan, scan BookDao, BookService
@ComponentScan("com.alex.autowired") @Configuration public class BookConfig { @Bean("bookdao2") public BookDao bookDao2() { BookDao bookDao = new BookDao(); bookDao.setId(1); bookDao.setName("alex"); return bookDao; }}Copy the code
BookDao
@Repository public class BookDao { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}Copy the code
BookService
@Service public class BookService { @Autowired private BookDao bookDao1; public void getBookById() { bookDao.getId(); } @Override public String toString() { return "BookService{" + "bookDao=" + bookDao + '}'; }}Copy the code
The test code
@Test public void test3() { AnnotationConfigApplicationContext ioc = getIoc(BookConfig.class); printBeans(ioc); BookService bookService = ioc.getBean(BookService.class); System.out.println(bookService); BookDao bookDao = ioc.getBean(BookDao.class); System.out.println(bookDao); } / / results bookConfig bookDao bookService bookService {bookDao = com. Alex. Autowired. BookDao @ 67 d18ed7} com.alex.autowired.BookDao@67d18ed7Copy the code
Conclusion: The BookDao object fetched from the BookService is the same as the BookDao object fetched directly from the container. @AutoWired is equivalent to passing the object BookDao from the container to the BookDao in the BookService
Multiple bookDAOs of the same type are injected
If there are multiple beans of the same type, an error is reported
No qualifying bean of type 'com.alex.autowired.BookDao' available: expected single matching bean but found 2: bookDao,bookDao2
Copy the code
BookDao and bookDao2 beans of the same type.
- The first error is that when a container has two BookDao objects of the same type, it can no longer get them from getBean(xxx.class), which is obviously a conflict
BookDao bookDao = ioc.getBean(BookDao.class);
System.out.println(bookDao);
Copy the code
- Second, when @AutoWired is injected, the object name should correspond to the bean name in the container so that there are no errors.
@Autowired
private BookDao bookDao;
Copy the code
- Solution 2
@qulifier ("bookDao") @autoWired Private bookDao;Copy the code
No assembly required = false
- If the object does not exist in the container, it may not be assembled
@autoWired (Required =false) private BookDao BookDao;Copy the code
@primary
@primary // specify @bean ("bookdao2") public BookDao Bookdao2 () {BookDao BookDao = new BookDao(); bookDao.setId(1); bookDao.setName("alex"); return bookDao; }Copy the code
@Resource
- Belongs to the Java specification
- As with Autowired, both assemblies are required by name and primary by name are not supported
- Recommended Autowired