采用注解形式来实现自动创建对象
@Component(value = "student")
public class Student {
@Value("自定义姓名")
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age-5;
}
public void setAge(int age) {
this.age = age;
}
}
<--组件扫描器 扫描com.spring下的所有类-->
<context:component-scan base-package="com.spring"></context:component-scan>
测试类
public class Client {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//此处为获取bean中的对象,第一个参数为bean中的id,第二个为对象类型
//当不写id的时候,默认的类名为类名首字母小写
Student student = context.getBean("student",Student.class);
System.out.println(student);
}
}
注意:@Service @Repository @Controller也可以分别写在三层上,剩下步骤如楼上(其实service层也可以写@Component,@Controller,因为作用都是当成一个组件去看待,但是习惯不好)
注解三层代码的实现~
applicationContext.xml
<--组件扫描器 扫描以下俩个包下的所有类-->
<context:component-scan base-package="com.spring.bean,com.spring.mvc"></context:component-scan>
@Service
public class StudentServiceImpl implements StudentService {
//如果有俩个类都实现了StudentDao,而且俩个类都写了注解,那么就不知道他该创建那个对象了,所以就要用到楼下的注解来指定创建哪个类的对象
//@Qualifier(value="studentDaoImpl")
//使用此注解,spring可以自动帮你把Bean里面引用类的对象的setter/getter方法省略掉,它会自动帮你set/get。
@Autowired
private StudentDao studentDao;
public void register(Student student) {
studentDao.insert(student);
}
}
测试类
public class Client {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//此处为获取bean中的对象,第一个参数为bean中的id,第二个为对象类型
StudentService studentService = context.getBean("service",StudentService.class);
studentService.register(null);
}
}
个性签名:一个人在年轻的时候浪费自己的才华与天赋是一件非常可惜的事情
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏5毛买辣条行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!