1.有参构造
package com.yyf.pojo;
public class User {
private String name;
public User(String name){
System.out.println ("我是有参构造"+name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println ("name+"+name);
}
}
2.无参构造
package com.yyf.pojo;
public class UserT {
private String name;
public UserT(){
System.out.println ("我是T参构造");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println ("name+"+name);
}
}
3.spring配置文件 有参构造这里有两种构造引入,一有参构造参数类型<constructor-arg type="java.lang.String" value="杨小法"/> 二。有参构造函数参数变量 <constructor-arg name="name" value="yang"/>--> 无参构造当bean对象被创建时就调用了无参构造
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.yyf.pojo.User">
<constructor-arg type="java.lang.String" value="杨小法"/>
</bean>
<!-- <bean id="user" class="com.yyf.pojo.User">-->
<!-- <constructor-arg name="name" value="yang"/>-->
<!-- </bean>-->
<bean id="usert" class="com.yyf.pojo.UserT"/>
<!-- <import resource="beans1.xml"/>-->
<!-- <import resource="beans2.xml"/>-->
<!-- 多人开发利用import将所有的配置文件集合在一起开发-->
</beans>
4.测试类
import com.yyf.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext ("beans.xml");
User user = (User) context.getBean ("user");
user.show ();
}
}