使用注解开发
1、spring4之后,必须导入AOP包
2、需要导入context约束,增加注解支持
<?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/>
</beans>
1、bean
@Component 等价于 <bean id="user" class="com.builddream.pojo.User"></bean>
2、属性如何注入
@Component
public class User {
public String name = "小明";
}
通过注解实现:
@Component
public class User {
// 等价于 <property name="name" value="张三"/>
@Value("张三")
public String name;
}
3、衍生注解
@Component 组件,相关衍生出如下注解,他们作用类似,按照webMvc三层架构:
dao 【@Repository】
service 【@Service】
controller 【@Controller】
4、自动装配
--@Autowire 按照属性类型进行装配
--@Nullable 表示当前类,或形参可以为空
--@Qualifer 指定名字装配
--@Resource 先按照名字装配,然后按照类型装配
5、作用域
略
6、小结
1、xml 用来管理bean
2、注解用来管理属性
3、如果需要让注解生效,那么必须开启注解的支持;
<context:component-scan base-package=“com.builddream”/>context:annotation-config/
Java实现配置
ApplicationContext.xml 通过java类来实现;Java 中bean对象注入容器
说明:通过@Configuartion 不需要配置Xml 一些配置文件,方法名相当于 bean的id,返回值相当于calss对应的类;@Bean相当于bean标签;
@Configuration
public class myconfig {
@Bean
public User getUser(){
return new User();
}
}
Java bean标签
说明:@Value相当于将name属性添加到class 为 User的bean中,其中@Component相当于根据byType在容器中查找,其类型值为User;
@Component
public class User {
@Value("李四")
public String name;
}
代码实现
MyTest
package com.builddream;
import com.builddream.controller.myconfig;
import com.builddream.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
/**
* @ClassName
* @Description
* @
* @date
* @Version 1.0
*/
public class MyTest {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(myconfig.class);
User user = (User) ac.getBean("getUser");
System.out.println(user.name);
}
}
User
package com.builddream.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @ClassName
* @Description
* @
* @date
* @Version 1.0
*/
@Component
public class User {
@Value("李四")
public String name;
}
myconfig
package com.builddream.controller;
import com.builddream.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
/**
* @ClassName
* @Description
* @
* @date
* @Version 1.0
*/
@Configuration
public class myconfig {
@Bean
public User getUser(){
return new User();
}
}