注解开发
配置文件
<?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
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="com.spring"/>
<!-- 开启注解开发 -->
<context:annotation-config></context:annotation-config>
</beans>
POJO
@Component// 作为组件注入 bean 相似于 <bean id="user" class="com.spring.pojo.User"/>
public class User {
// 值的注入相似于咱们的 <property name="name" value="张三"></property>
@Value("张三")
private String name;
public String getName() {return name;}
}
Dao
@Repository// 注入默认为 Dao 层对应三层架构的数据长久层
public class UserDao {
private User user;
@Autowired
public UserDao(User user){this.user = user;}
public void getName(){System.out.println(user.getName());
}
}
Service
@Service// 注入默认为 Service 层对应三层架构的业务层
public class UserService {
public UserDao userDao;
@Autowired
public UserService(UserDao userDao){this.userDao = userDao;}
public void getName(){userDao.getName();
}
}
Controller
@Controller// 注入默认为 Controller 层对应三层架构的管制层层
public class UserController {
private UserService userService;
@Autowired
public UserController(UserService userService){this.userService=userService;}
public void getName(){userService.getName();
}
}
启动类
public class AnnotationTest {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
UserController userDao = context.getBean("userController", UserController.class);
userDao.getName();}
}
纯注解开发
配置文件
/**
* 表明该类是 Spring 的配置类
* 相似于咱们的 xml 文件
* 这个类也会交给 Spring 治理,@Configuration 蕴含 @Component 注解
*/
@Configuration
/**
* 包扫描相似于 <context:component-scan base-package="com.spring"/>
*/
@ComponentScan("com.spring")
/**
* 导入另一个配置文件
* 相似于 <import resource="springConfig2.xml"></import>
*/
@Import(SpringConfig2.class)
public class SpringConfig {
/**
* 相似于 <bean></bean>
* 注入了一个对象
* 办法名是 id 属性
* 办法返回值的类型是 class 属性
*/
@Bean
public User user(){return new User();
}
}