现行主流的开发是以注解为主的
5 注解开发
<context:annotation-config/>
开启注解支持<context:component-scan base-package="com.cap.pojo" />
组件扫描,将扫描指定路径下的所有类,类上含有@Component
注解的类都会当成一个bean加载进容器@Component
的特殊注解(下面这三者注解和@Component是等同的)@Repository
:持久层@Service
:业务层@Controller
:控制层
<?xml version="1.0" encoding="UTF-8"?>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.cap.pojo" />
</beans>
@Component
public class User {
private String name;
public String getName() {
return name;
}
}
6 完全Java开发
我们不使用xml配置文件的情况下进行开发
@Component
public class User {
@Value("公孙离")
private String name;
public User(){
System.out.println("User is instancing~~~");
}
public String getName() {
return name;
}
}
package com.cap.config;
@Configuration
public class Config {
@Bean
User getUser(){
return new User();
}
}
@Test
public void test(){
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
User user = context.getBean(User.class);
System.out.println(user);
System.out.println(user.getName());
}
结果得到
User is instancing~~~
com.cap.pojo.User@6cd24612
公孙离