注解开发定义bean
不指定名称
package org.example.service.impl;
import org.example.dao.BookDao;
import org.example.service.BookService;
import org.springframework.stereotype.Component;
@Component
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();
}
}
指定名称
package org.example.dao.impl;
import org.example.dao.BookDao;
import org.springframework.stereotype.Component;
@Component("bookDao")
public class BookDaoimpl implements BookDao {
@Override
public void save() {
System.out.println("book dao save");
}
}
xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!-- 开启context命名空间-->
<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
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.example.dao.impl"/>
<context:component-scan base-package="org.example.service.impl"/>
</beans>
package org.example;
import org.example.dao.BookDao;
import org.example.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class AppForDIAtuoware {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = (BookDao) ctx.getBean("bookDao");
bookDao.save();
BookService bookService=ctx.getBean(BookService.class);
System.out.println(bookService);
}
}
衍生注解