Spring创建的对象称为Bean
<bean id="hello" name="beanName1,beanName2" class="com.ding.entity.Hello">
<property name="str" value="Spring"/>
</bean>
id = 变量名,可以通过id值获取bean
class : bean的类型相当于new出来的对象
name: bean的别称也可以获取bean
property: 相当于给对象的属性设置一个值
测试对象
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
}
<bean id="address" class="com.ding.entity.Address"
<property name="address" value="阜阳" /><!--普通注入-->
</bean>
<bean id="address" class="com.ding.entity.Student"
<property name="name" value="jeff" /><!--普通注入-->
<!--引用注入-->
<property name="address" ref="address"/>
<!--数组-->
<property name="books">
<array>
<value>java程序设计</value>
<value>javaweb</value>
</array>
</property>
<!--List-->
<property name="hobbies">
<list>
<value>打篮球</value>
<value>看电影</value>
<value>敲代码</value>
</list>
</property>
<!--Map-->
<property name="card">
<map>
<entry key="身份证" value="123456789987456321"/>
<entry key="银行卡" value="359419496419481649"/>
</map>
</property>
<!--Set -->
<property name="games">
<set>
<value>LOL</value>
<value>COC</value>
<value>BOB</value>
</set>
</property>
<!--NULL-->
<property name="wife">
<null/>
</property>
<!--Properties-->
<property name="info">
<props>
<prop key="driver">111</prop>
<prop key="url">1111</prop>
<prop key="user">jeff</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>
ByName自动装配
会自动在容器上下文中查找,和自己对象set方法后面对应的bean id
<bean id="people" class="com.ding.entity.People" autowire="byName">
<property name="name" value="jeff"/>
</bean>
ByType自动装配
会自动在容器上下文中查找,和自己对象属性类型相同的bean
<bean id="people" class="com.ding.entity.People" autowire="byType">
<property name="name" value="jeff"/>
</bean>
@Component
//等价于<bean id="user" class="com.ding.entity.User"/>
//@Component 组件
@Component
public class User {
//相当于 <property name="name" value="小明"/>
@Value("小明")
public String name;
}
dao 【@Repository】
service 【@Service】
controller 【@Controller】
这几个都相当于@Component
@Autowired
public class People {
//如果显式定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
@Autowired(required = false)
private Cat cat;
@Autowired
@Qualifier(value = "dog")//指定@Qualifier后可以指定自动装配的bean的id
private Dog dog;
private String name;
}
// @Configuration代表这是一个配置类相当于xml
@Configuration
@ComponentScan("com.ding.entity")//扫描包
@Import(Config2.class)
public class SpringConfig {
// 注册一个bean,就相当于我们之前写的一个bean标签
// 这个方法的名字,就相当于bean标签中id属性
// 这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User user(){
return new User(); // 就是返回要注入到bean的对象!
}
原文:https://www.cnblogs.com/dss-99/p/15096923.html